簡體   English   中英

如何防止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 ,我將foo重寫為:

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

按值返回對象時您將返回一個臨時對象臨時對象將立即被銷毀除非它被復制或綁定到調用方的變量中。

您在做錯的是將引用綁定到返回的臨時對象包含的內容,而不是返回的對象本身。 到您訪問的對象所綁定的對象在銷毀時已被臨時對象的析構函數刪除。

為了說明您做錯了什么,我使用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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM