对于c++语法中unique_ptr粗浅的认知

对于c++语法中unique_ptr粗浅的认知

unique_ptr 与malloc和new的区别在于他是会自动释放的

#include <iostream>
#include <memory>

struct Task {
    int mId;
    Task(int id ) :mId(id) {
        std::cout << "Task::Constructor" << std::endl;
    }
    ~Task() {
        std::cout << "Task::Destructor" << std::endl;
    }
};

void test()
{
    // 通过原始指针创建 unique_ptr 实例
    std::unique_ptr<Task> taskPtr(new Task(23));
    printf("%p\n",taskPtr.get());

    int id = taskPtr->mId;
    //通过 unique_ptr 访问其成员
    std::cout << id << std::endl;
}

int main()
{
    test();
    return 0;
}
发布了93 篇原创文章 · 获赞 2 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_32783703/article/details/103417105