std::unique_ptr用法
copy from : https://blog.csdn.net/piaopiaopiaopiaopiao/article/details/87912137
-
-
-
-
struct Task {
-
int mId;
-
Task(int id) : mId(id) {
-
std::cout << "Task::Constructor" << std::endl;
-
}
-
~Task() {
-
std::cout << "Task::Destructor" << std::endl;
-
}
-
};
-
-
int main() {
-
//空unique_ptr对象
-
std::unique_ptr<int> ptr1;
-
-
//检查unique_ptr对象是否为空
-
if (!ptr1) {
-
std::cout << "ptr1 is empty" << std::endl;
-
}
-
-
//检查unique_ptr对象是否为空
-
if (ptr1 == nullptr) {
-
std::cout << "ptr1 is empty" << std::endl;
-
}
-
-
//不能通过赋值初始化创建unique_ptr对象
-
//std::unique_ptr<Task> taskPtr2 = new Task(); //编译错误
-
-
//通过原始指针创建unique_ptr对象
-
std::unique_ptr<Task> taskPtr(new Task(23));
-
-
//检查taskPtr是否为空,或者是否有关联的原始指针
-
if (taskPtr != nullptr) {
-
std::cout << "taskPtr is not empty" << std::endl;
-
}
-
-
//通过unique_ptr访问内部元素
-
std::cout << taskPtr->mId << std::endl;
-
-
std::cout << "Reset the taskPtr" << std::endl;
-
//重置unique_ptr将删除关联的原始指针,并使unique_ptr对象为空
-
taskPtr.reset();
-
-
//检查taskPtr是否为空,或者是否有关联的原始指针
-
if (taskPtr == nullptr) {
-
std::cout << "taskPtr is empty" << std::endl;
-
}
-
-
//通过原始指针创建unique_ptr对象
-
std::unique_ptr<Task> taskPtr2(new Task(55));
-
-
if (taskPtr2 != nullptr) {
-
std::cout << "taskPtr2 is not empty" << std::endl;
-
}
-
-
//unique_ptr 对象不可复制
-
//taskPtr = taskPtr2; //编译错误
-
-
//unique_ptr 对象不可复制
-
//std::unique_ptr<Task> taskPtr3 = taskPtr2; //编译错误
-
-
{
-
//转移所有权
-
std::unique_ptr<Task> taskPtr4 = std::move(taskPtr2);
-
-
if (taskPtr2 == nullptr) {
-
std::cout << "taskPtr2 is empty" << std::endl;
-
}
-
-
//taskPtr2的所有权转移给了task4
-
if (taskPtr4 != nullptr) {
-
std::cout << "taskPtr4 is not empty" << std::endl;
-
}
-
-
std::cout << taskPtr4->mId << std::endl;
-
//taskPtr4超出范围并删除关联的原始指针
-
}
-
-
//通过原始指针创建unique_ptr对象
-
std::unique_ptr<Task>taskPtr5(new Task(55));
-
-
if (taskPtr5 != nullptr) {
-
std::cout << "taskPtr5 is not empty" << std::endl;
-
}
-
-
//从原始指针释放对象的所有权
-
Task* ptr = taskPtr5.release();
-
-
if (taskPtr5 == nullptr) {
-
std::cout << "taskPtr5 is empty" << std::endl;
-
}
-
-
std::cout << ptr->mId << std::endl;
-
-
delete ptr;
-
-
return 0;
-
}
-
Always Believe Something Beauitful Will Be Happen