本人正在看《c++ primer》第五版中文版,关于unique_ptr。
在第418页,书上说:
unique_ptr的release()只是放弃对指针的控制权,返回指针,并将本人置为空。
换句话说,release并不会调用delete。所以我们可以这样:
unique_ptr<int> up(new int(10));
unique_ptr<int> up2(up.release());
而在第425页是这样写的:
unique_ptr<int[]> up(new int[10]());
up.release(); // 自动delete[]销毁其指针
这里本人就不清楚了,怎么release又自动调用delete[]了?前面说release不会delete而只是放弃对指针的控制权啊?
是本人理解有问题还是书上写错了?
在第418页,书上说:
unique_ptr的release()只是放弃对指针的控制权,返回指针,并将本人置为空。
换句话说,release并不会调用delete。所以我们可以这样:
unique_ptr<int> up(new int(10));
unique_ptr<int> up2(up.release());
而在第425页是这样写的:
unique_ptr<int[]> up(new int[10]());
up.release(); // 自动delete[]销毁其指针
这里本人就不清楚了,怎么release又自动调用delete[]了?前面说release不会delete而只是放弃对指针的控制权啊?
是本人理解有问题还是书上写错了?
解决方案
5
release 只是释放控制权,不会释放内存。
释放内存可以用 reset(nullptr);
释放内存可以用 reset(nullptr);
5
Use release to take over ownership of the raw pointer stored by the unique_ptr. The caller is responsible for deletion of the returned pointer. The unique-ptr is set to the empty default-constructed state. You can assign another pointer of compatible type to the unique_ptr after the call to release.
https://msdn.microsoft.com/en-us/library/ee475597.aspx
https://msdn.microsoft.com/en-us/library/ee475597.aspx
20
书上写错了,你可以把unique_ptr的deleter重载,再分别调用release和reset,可以看到只有后者真的执行了deleter。
5
release 不会调用 delete 的。可以 unique_ptr<自定义类> 看析构函数。
5
Releases ownership of its stored pointer, by returning its value and replacing it with a null pointer.
This call does not destroy the managed object, but the unique_ptr object is released from the responsability of deleting the object. Some other entity must take responsibility for deleting the object at some point.
To force the destruction of the object pointed, either use member function reset or perform an assignment operation on it.
This call does not destroy the managed object, but the unique_ptr object is released from the responsability of deleting the object. Some other entity must take responsibility for deleting the object at some point.
To force the destruction of the object pointed, either use member function reset or perform an assignment operation on it.