这是后续问题。
我们如何获得std :: unique_ptr或std :: shared_ptr的所有权?
有没有办法让b活着?
class A{ public: A() { b = std::unique_ptr<char[]>(new char[100] { 0 }); } char* b; } void func { A a; }This is follow-up question for this.
How do we take ownership of a std::unique_ptr or std::shared_ptr?
Is there a way to to keep b alive?
class A{ public: A() { b = std::unique_ptr<char[]>(new char[100] { 0 }); } char* b; } void func { A a; }最满意答案
要获取指针的所有权,请使用std::unique_ptr::release() :
释放被管理对象的所有权(如果有的话)。
返回值 。 如果没有托管对象,则指向托管对象或nullptr指针,即在调用之前由get()返回的值。
话虽这么说,我不确定你为什么要做b = std::unique_ptr<char[]>(new char[100] { 0 }).release(); 。 也许你想要的是这个,即A本身存储unique_ptr ?
class A { A() : b(new char[100] { 0 }) { } private: std::unique_ptr<char[]> b; }现在,每当A实例被破坏时, Ab指向的内存将被释放。
To take ownership of the pointer, use std::unique_ptr::release():
Releases the ownership of the managed object if any.
Return value. Pointer to the managed object or nullptr if there was no managed object, i.e. the value which would be returned by get() before the call.
That being said, I'm not sure why you'd ever want to do b = std::unique_ptr<char[]>(new char[100] { 0 }).release();. Maybe what you want is this, i.e. have A itself store the unique_ptr?
class A { A() : b(new char[100] { 0 }) { } private: std::unique_ptr<char[]> b; }Now, whenever an A instance is destructed, the memory pointed to by A.b will be freed.
如何取得std :: unique_ptr和std :: shared_ptr的所有权(How to take ownership of std::unique_ptr and std::shared_ptr)这是后续问题。
我们如何获得std :: unique_ptr或std :: shared_ptr的所有权?
有没有办法让b活着?
class A{ public: A() { b = std::unique_ptr<char[]>(new char[100] { 0 }); } char* b; } void func { A a; }This is follow-up question for this.
How do we take ownership of a std::unique_ptr or std::shared_ptr?
Is there a way to to keep b alive?
class A{ public: A() { b = std::unique_ptr<char[]>(new char[100] { 0 }); } char* b; } void func { A a; }最满意答案
要获取指针的所有权,请使用std::unique_ptr::release() :
释放被管理对象的所有权(如果有的话)。
返回值 。 如果没有托管对象,则指向托管对象或nullptr指针,即在调用之前由get()返回的值。
话虽这么说,我不确定你为什么要做b = std::unique_ptr<char[]>(new char[100] { 0 }).release(); 。 也许你想要的是这个,即A本身存储unique_ptr ?
class A { A() : b(new char[100] { 0 }) { } private: std::unique_ptr<char[]> b; }现在,每当A实例被破坏时, Ab指向的内存将被释放。
To take ownership of the pointer, use std::unique_ptr::release():
Releases the ownership of the managed object if any.
Return value. Pointer to the managed object or nullptr if there was no managed object, i.e. the value which would be returned by get() before the call.
That being said, I'm not sure why you'd ever want to do b = std::unique_ptr<char[]>(new char[100] { 0 }).release();. Maybe what you want is this, i.e. have A itself store the unique_ptr?
class A { A() : b(new char[100] { 0 }) { } private: std::unique_ptr<char[]> b; }Now, whenever an A instance is destructed, the memory pointed to by A.b will be freed.
发布评论