为什么返回构造函数时没有副本?

时间:2016-07-09 03:12:14

标签: c++ visual-c++

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。

0 个答案:

没有答案