[英]Empty user-defined move constructor
我編寫的理解移動CTOR行為的以下代碼片段使我很難理解其輸出:
#include <iostream>
class Temp
{
public:
Temp(){
std::cout << "Temp DEFAULT CTOR called" << std::endl;
mp_Val = nullptr;
}
Temp(int inp) {
std::cout << "Temp CTOR called" << std::endl;
mp_Val = new int(inp);
}
Temp(const Temp& inp) {
std::cout << "Temp COPY CTOR called" << std::endl;
mp_Val = new int(*inp.mp_Val);
}
Temp& operator= (const Temp& inp) {
std::cout << "Temp ASSIGNMENT OPER called" << std::endl;
mp_Val = new int(*inp.mp_Val);
return *this;
}
int* mp_Val;
};
class B
{
public:
B(){
std::cout << "Class B DEFAULT CTOR" << std::endl;
mp_Val = nullptr;
}
B(int inp) {
std::cout << "Class B CTOR" << std::endl;
mp_Val = new Temp(inp);
}
B(const B& in) {
std::cout << "Class B COPY CTOR" << std::endl;
mp_Val = in.mp_Val;
}
B(B&& in){
std::cout << "Class B MOVE CTOR" << std::endl; //Doubt: 1
}
Temp *mp_Val;
};
int main() {
B obj1(200);
B obj2 = std::move(obj1);
auto temp = obj1.mp_Val;
std::cout << "Obj1 B::Temp address: " << obj1.mp_Val << std::endl;
std::cout << "Obj2 B::Temp address: " << obj2.mp_Val << std::endl; //Doubt: 2
return 0;
}
輸出:
Class B CTOR
Temp CTOR called
Class B MOVE CTOR
Obj1 B::Temp address: 0xd48030
Obj2 B::Temp address: 0x400880
GCC版本:4.6.3
我的問題是關於標記為“懷疑2”的行。地址不應該打印為0嗎? 根據我的理解,由於我在class B
定義了一個空移動CTOR(標記為“懷疑1”),因此應調用Temp
類的默認CTOR(從日志中看不到它的調用)來初始化其成員變量mp_Val
。輸入Temp
。
很明顯,我缺少一些東西。
根據我的理解,由於我在
class B
定義了一個空移動CTOR(標記為“懷疑1”),因此應調用Temp
類的默認CTOR(從日志中看不到它的調用)來初始化其成員變量mp_Val
。輸入Temp
。
您的成員變量不是Temp
類型,而是Temp *
類型。 沒錯,缺少初始化程序意味着該成員將是默認構造的,而對於Temp
類型,將涉及調用默認構造函數。 但是,對於指針類型,默認構造使該對象未初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.