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 秒后退出,return 值为 0
按任意键继续 。 . .

main中定义的whereDidThisGo变量的construction/destruction在哪里?

直到大约 NRVO,对于像我这样正在尝试学习构造函数的人来说,这不是一个很好的优化哈哈。

谢谢你的回答,是的,移动赋值应该是一个non-const指针,我只是忽略了它。

Where is the construction/destruction of the whereDidThisGo variable defined in main?

由于命名 return 值优化(又名 NRVO),您看不到此输出。

it's not a good optimization for people like me who are trying to learn constructors

您可以通过向编译器提供 -fno-elide-constructors 标志来 禁用 此 NRVO。 Demo.


此外,请注意,在您的示例中,A::operator=(const A&&) 应该改为:

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