class Test {
public:
Test() { OutputDebugStringA("Construct\n"); };
~Test() { OutputDebugStringA("Destruct\n"); };
Test(const Test& other) { OutputDebugStringA("Copy Construct\n"); }
Test& operator = (const Test& other) {
OutputDebugStringA("Copy Construct\n");
return *this;
}
Test GetNewTest() const {
OutputDebugStringA("GetNewTest\n");
return Test();
}
};
int main() {
Test test;
Test new_test = test.GetNewTest();
return 0;
}
输出
Construct
GetNewTest
Construct
Destruct
Destruct
所以我认为return Test();
不会为返回值创建新的Test
和副本。它是用C ++标准定义的还是它的编译器优化行为?我正在使用VS2015。