[英]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_ptr
對unique_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.