簡體   English   中英

unique_ptr 所有權瘋狂

[英]unique_ptr ownership craziness

看看下面的示例代碼和它的輸出。

我有一個簡單的Base類,只有一個int*成員變量。

我從 Base 的現有對象創建了一個 unique_ptr。

當指針和對象超出范圍時,析構函數會被調用兩次,首先是針對 unique_ptr,然后是針對對象。

我認為 unique_ptr 將擁有該對象並負責銷毀它?

#include <iostream>
#include <string>
#include <vector>
#include <memory>

class Base
{
protected:
    int* status;

public:
    // default constuctor
    Base() : Base(0)
    {
    }

    // custom constuctor
    Base(int a){
        this->status = new int(a);
        std::cout << "\n" << "Base:" << *status;
    }

    // destructor
    ~Base(){
        std::cout << "\n" << "Base Destroyed:" << *status;
        delete this->status;
    }

    void info(){
        std::cout << "\n" << "Base status:" << *status;
    }    
};

int main(int argc, const char * argv[])
{
    {
        Base base(1);

        // create from existing object
        std::unique_ptr<Base> uptrBase1 = std::make_unique<Base>(base);

        // create from new
        std::unique_ptr<Base> uptrBase3 = std::make_unique<Base>();

        std::cout<<"\n" << "Ending scope";
    }

    std::cout<<"\n";
    return 0;
}

我得到的輸出如下:

Base:1
Base:0
Ending scope
Base Destroyed:0
Base Destroyed:1
Base Destroyed:0TestCppProject(4373,0x1000d5dc0) malloc: *** error for object 0x1005ac970: pointer being freed was not allocated
TestCppProject(4373,0x1000d5dc0) malloc: *** set a breakpoint in malloc_error_break to debug
Program ended with exit code: 9

我認為 unique_ptr 將擁有該對象並負責銷毀它?

您不能擁有自動存儲持續時間對象的所有權。 這些對象的生命周期由編譯器控制,並在它們定義的塊的末尾結束。 時期。 此行的作用:

std::unique_ptr<Base> uptrBase1 = std::make_unique<Base>(base);

它創建動態存儲持續時間對象並使用base對其進行初始化。 即邏輯上這段代碼等於:

Base *ptr = new Base( base );
std::unique_ptr<Base> uptrBase1( ptr );

所以你復制了一個base並將這個新創建的對象的所有權交給uptrBase1 因為你違反了什么是三定律? 這導致 UB 由於您在類Base創建的內部指針的雙重破壞,並且當您創建了 3 個Base類型的對象時,它的析構函數被調用了 3 次。

順便說一句:如果您遵循慣例並使status std::unique_ptr編譯器將不允許您違反規則,並且前面提到的行將無法編譯。

暫無
暫無

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

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