这是一个 r 值实验,但是当 gcc 向我抱怨缺少移动构造函数(我已经删除它)并且没有回退到复制构造函数(如我所料)时它发生了变异,然后我删除了 -std= c++11 从标志并尝试了您在下面看到的内容,它有很多输出(最初没有),因为我正在尝试找出它为什么不起作用(我知道如何调试,但我发现标准输出上的消息可以很好地指示正在发生的事情)
这是我的代码:
#include <iostream>
class Object {
public:
Object() { id=nextId; std::cout << "Creating object: "<<id<<"\n"; nextId++; }
Object(const Object& from) {
id=nextId; std::cout << "Creating object: "<<id<<"\n"; nextId++;
std::cout<<"(Object: "<<id<<" created from Object: "<<from.id<<")\n";
}
Object& operator=(const Object& from) {
std::cout<<"Assigning to "<<id<<" from "<<from.id<<"\n";
return *this;
}
~Object() { std::cout<<"Deconstructing object: "<<id<<"\n";}
private:
static int nextId;
int id;
};
int Object::nextId = 0;
Object test();
int main(int,char**) {
Object a;
std::cout<<"A ought to exist\n";
Object b(test());
std::cout<<"B ought to exist\n";
Object c = test();
std::cout<<"C ought to exist\n";
return 0;
}
Object test() {
std::cout<<"In test\n";
Object tmp;
std::cout<<"Test's tmp ought to exist\n";
return tmp;
}
输出:
Creating object: 0
A ought to exist
In test
Creating object: 1
Test's tmp ought to exist
B ought to exist
In test
Creating object: 2
Test's tmp ought to exist
C ought to exist
Deconstructing object: 2
Deconstructing object: 1
Deconstructing object: 0
我使用解构,因为解构已经是一个词,有时我使用析构函数,我对这个词不太满意,我喜欢析构函数作为名词。
这是我的预期:
A to be constructed
tmp in test to be constructed, a temporary to be created from that
tmp, tmp to be destructed(?)
that temporary to be the argument to B's copy constructor
the temporary to be destructed.
C's default constructor to be used
"" with a temporary from `test`
C's assignment operator to be used
the temporary to be destructed
c,b,a to be destructed.
我被称为“顽固的 C”,我正在尝试学习使用 C++,而不是“C with namespaces”。
有人可能会说“编译器优化了它”我希望那个人现在或永远不要用这样的答案回答问题,优化不能改变程序状态,就好像一切都按照规范所说的那样发生,所以编译器可能会通过在 cout 上添加包含数字的消息来取笑我,它甚至可能不会费心增加数字等,但程序的输出将与它确实完成了代码描述的所有操作一样。
所以这不是优化,发生了什么?