簡體   English   中英

具有結構指針的類初始化列表

[英]Class initialization list with struct pointer

我正在看一個PIMPL習慣用法的示例,我發現了我真的不懂的代碼行。 由於我是C ++和OOP的新手,所以我希望有人可以解釋此函數的作用。

有人可以澄清這個功能嗎?

PublicClass::PublicClass(const PublicClass& other)
    : d_ptr(new CheshireCat(*other.d_ptr)) { // <------- This line 
    // do nothing
}

/

這是例子。

//header file:
class PublicClass {
public:
    PublicClass();                              // Constructor
    PublicClass(const PublicClass&);            // Copy constructor
    PublicClass(PublicClass&&);                 // Move constructor
    PublicClass& operator=(const PublicClass&); // Copy assignment operator
    ~PublicClass();                             // Destructor
    // Other operations...

private:
    struct CheshireCat;                         // Not defined here
    unique_ptr<CheshireCat> d_ptr;              // opaque pointer
};

/

//CPP file:
#include "PublicClass.h"

struct PublicClass::CheshireCat {
    int a;
    int b;
};

PublicClass::PublicClass()
    : d_ptr(new CheshireCat()) {
    // do nothing
}

PublicClass::PublicClass(const PublicClass& other)
    : d_ptr(new CheshireCat(*other.d_ptr)) {
    // do nothing
}

PublicClass::PublicClass(PublicClass&& other) 
{
    d_ptr = std::move(other.d_ptr);
}

PublicClass& PublicClass::operator=(const PublicClass &other) {
    *d_ptr = *other.d_ptr;
    return *this;
}

PublicClass::~PublicClass() {}

結構不“取值”。 函數取值。 構造函數是函數。 new CheshireCat(*other.d_ptr) ,您調用編譯器生成CheshireCat 副本構造函數

也不傳遞指針而是引用,因為您通過std::unique_ptr的重載operator*解除了對other.d_ptr的引用。 實際上,如果您編寫了new CheshireCat(other.d_ptr)new CheshireCat(other.d_ptr.get()) ,則會出現編譯錯誤。

表達式*other.d_ptr被解析為與*(other.d_ptr)等效。 讓我們采用語法d_ptr(new CheshireCat(*other.d_ptr))並由內而外地確定它在做什么:

  • other PublicClass const &聲明。
  • other.d_ptr -一個unique_ptr<CheshireCat> const &到一個參考d_ptr的實例成員other
  • *other.d_ptrunique_ptr對象的operator*的調用,這將產生CheshireCat const &類型的結果(對unique_ptr對象擁有的對象的引用)。
  • new CheshireCat(*other.d_ptr) -使用此CheshireCat const &並通過調用CheshireCat類型的副本構造函數來堆分配新的CheshireCat對象。 此表達式的類型為CheshireCat *
  • d_ptr(new CheshireCat(*other.d_ptr)) -使用CheshireCat *值構造正在構造的PublicClass對象的d_ptr成員。 (這是此特定PublicClass構造函數的初始化列表 。)

換句話說,這行所做的只是復制other實例擁有的CheshireCat對象,並將該副本的所有權提供給正在構造的PublicClass對象。

當用戶未定義C ++時,默認情況下C ++提供了一個復制構造函數: http : //en.cppreference.com/w/cpp/language/copy_constructor

該行:

d_ptr(new CheshireCat(*other.d_ptr))

只是簡單地取消引用指向現有CheshireCat對象的指針,然后將其復制以實例化d_ptr指向該實例化對象所指向的新CheshireCat對象。

暫無
暫無

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

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