我希望了解更多关于C++的内容,但是对于我的编译器所做的事情还有些困惑。下面是我写的一个文件,并在注释中详细说明了发生了什么:
Test getTest()
{
return Test(100, string("testing..."));
}
int main()
{
// These two will call the initializer constructor...
Test t1(5, string("hello"));
Test t2(10, string("goodbye"));
// This will not call operator=. This will call the copy constructor!
Test t3 = t1;
// This will call operator=(Test&)
t3 = t2;
// This will call operator=(Test&&) because rhs is an rvalue
// We will swap the resources in this operator= so that when getTest()
// deletes its resources, it will actually be deleting t3's old resources.
// Likewise, t3 will get getTest()'s resources.
t3 = getTest();
// I don't know what this is doing, but I know it's not calling the destructor.
// I beleive that the memory of t4 is simply what was returned by getTest().
// Likewise with t5.
Test t4(getTest());
Test* t5 = new Test(getTest());
Test t6(t4);
return 0;
}
似乎t4和t5没有进入任何构造函数,实际上只是使用getTest()分配的内存。我原以为t4会进入rValue复制构造函数: Test(const Test&& rhs), 但它并没有,尽管它的参数是一个rValue。Test t4(getTest())不调用任何析构函数,这就是为什么我认为t4只是获取了内存。t6调用了复制构造函数。
我查看了Visual Studio 2013中的汇编代码,发现以下内容:
Test t4(getTest());
00F59B8C push 8
00F59B8E lea ecx,[t4]
00F59B91 call Test::__autoclassinit2 (0F51285h)
00F59B96 lea eax,[t4]
00F59B99 push eax
00F59B9A call getTest (0F51456h)
00F59B9F add esp,4
00F59BA2 mov byte ptr [ebp-4],8
看起来它在调用autoclassinit2,然后从getTest中获取内存,最后将其存储在t4中?
所以我的问题是:这只是编译器优化,直接将构造函数中的内存从getTest()传递给t4吗?而不是说,1. 在getTest()中构造 2. 调用rVal复制构造函数 3. 销毁getTest()内存?还是其他什么事情发生了?谢谢!