如何获得 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;
}
要获得指针的所有权,请使用 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.
话虽这么说,但我不确定您为什么要这样做 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
实例被销毁时,A.b
指向的内存将被释放。
这是
我们如何获得 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;
}
要获得指针的所有权,请使用 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 byget()
before the call.
话虽这么说,但我不确定您为什么要这样做 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
实例被销毁时,A.b
指向的内存将被释放。