如何防止 unique_ptr 内存丢失

How do I prevent the memory loose from unique_ptr

下面这段代码会导致内存丢失,因为rA在构造时被初始化为无效。我什么时候可以解决这个问题?

使用 shared_ptr 还是希望未来的编译器版本能够捕获此错误代码?

#include <memory>
using namespace std;

struct A {};
void use(const A& a) {};

unique_ptr<A> foo()
{
    unique_ptr<A> pa(new A());
    return pa;
}

int main()
{
    const A& rA = *foo(); // rA is unusable, initialized with invalid reference (invalidated by destruction of temporary unique_ptr returned from foo)
    use(rA);
}

将您的 main 重写为:

int main()
{
   auto a = foo();

   use(*a);
}

顺便说一句,我将 foo 重写为:

std::unique_ptr<A> foo()
{
    return std::make_unique<A>();
}

当你return对象按值你return一个临时将被销毁立即除非从调用方复制或绑定到变量。

您做错的是将引用绑定到 returned 临时对象 包含 而不是 returned 对象本身。当你访问你绑定的东西时,临时对象的析构函数在它被销毁时已经删除了对它的引用。

为了说明您做错了什么,我使用 std::vector 编写了一个等效示例并将引用绑定到其中一个元素:

void use(const int& a) {}

std::vector<int> foo()
{
    return {1, 2, 3};
}

int main()
{
    const int& rA = foo()[0]; // bind to an element
    // the vector itself is destroyed by the time we get here

    use(rA); // whoops using a reference to an element from a destroyed vector
}