gpt4 book ai didi

c++ - 如何取得 std::unique_ptr 和 std::shared_ptr 的所有权

转载 作者:行者123 更新时间:2023-11-30 01:12:50 24 4
gpt4 key购买 nike

这是 this 的后续问题.

我们如何获取 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指向的内存将被释放。

关于c++ - 如何取得 std::unique_ptr 和 std::shared_ptr 的所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33429100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com