簡體   English   中英

c ++缺少對象的構造和銷毀

[英]c++ missing construction and destruction of an object

以下代碼:

#include <iostream> 
#include <string>
using namespace std;
void print(string a) { cout << a << endl; }
void print(string a, string b) { cout << a << b << endl; }
 
class A {
    public:
    string p;
    A() { print("default constructor"); }   
    A(string a){ p = a; print("string constructor ", p); }
    A(const A& o) { print("copy constructor"); }
    A (A&& o) { print("move constructor"); }
    A& operator=(const A& o) { print("copy assignment"); return *this; }
    A& operator=(const A&& o) { cout << "move assignment to:" << p << " from:" << o.p << endl; return *this; }
    ~A() { print("destructor ", p); }
};

A operator+(const A& a, const A& b) { 
    cout << "add" <<endl; 
    A c("f"); 
    return c;
}
    
A f(A& a, A& b, A& c) {
    A d("e");
    d = a+b+c;
    print("after add");
    return d;
}

int main() {
    A a("a"); A b("b"); A c("c");
    A whereDidThisGo {f(a,b,c)};
    print("end");
}

具有以下輸出:

string constructor a
string constructor b
string constructor c
string constructor e
add
string constructor f
add
string constructor f
move assignment to:e from:f
destructor f
destructor f
after add
end
destructor e
destructor c
destructor b
destructor a

進程在 0.06744 秒后退出,返回值為 0
按任意鍵繼續 。 . .

main 中定義的 whereDidThisGo 變量的構造/銷毀在哪里?

main 中定義的 whereDidThisGo 變量的構造/銷毀在哪里?

由於命名返回值優化(又名 NRVO),您看不到此輸出。

對於像我這樣試圖學習構造函數的人來說,這不是一個好的優化

您可以通過向編譯器提供-fno-elide-constructors標志來禁用此 NRVO。 演示


另外,請注意,在您的示例中, A::operator=(const A&&)應該是:

//-----------vv------->no need for const  here
A::operator=(A&&)

TIL 關於NRVO ,對於像我這樣正在嘗試學習構造函數的人來說,這不是一個好的優化哈哈。

謝謝你的回答,是的,移動賦值應該是一個非常量指針,我只是忽略了它。

暫無
暫無

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

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