我试着理解这个分配在c ++中是如何工作的:
Test other = toto();
Run Code Online (Sandbox Code Playgroud)
这是完整的代码源:
#include <iostream>
class Test
{
public:
Test()
{
j = i++;
std::cout<<"default constructor "<<j<<std::endl;
}
Test(const Test&)
{
std::cout<<"constuctor by copy "<<j<<std::endl;
}
Test & operator=(const Test&)
{
std::cout<<"operator = "<<j<<std::endl;
return *this;
}
int j;
static int i;
};
int Test::i = 0;
Test toto()
{
Test t;
return t;
}
int main()
{
Test other = toto();
std::cout<<other.j<<std::endl;
Test another;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码没有通过copy或operator =使用构造函数,所以我真的不明白它是如何工作的...我使用的是gcc 4.7.0
帮助你的帮助:)
杰罗姆
格式语义:
Test other = toto();
Run Code Online (Sandbox Code Playgroud)
涉及多个副本(但没有任务).但是,编译器可以忽略所有不同的实例,从而消除了副本; 几乎所有的编译器都做了这个优化.
更具体地说,标准没有指定返回类类型值的位置,但通常的解决方案是让调用者分配空间,并将一个隐藏指针传递给函数.没有上面提到的优化:
Test
toto()
{
Test t;
return t;
}
Run Code Online (Sandbox Code Playgroud)
将导致t构造局部变量,然后return语句将复制t到隐藏指针指向的空间.这里的优化(称为命名返回值优化,或NRVO)导致编译器使用隐藏指针指向的空间t,而不是t在本地创建单独的空间.(显然,它这样做的时候,它并没有破坏t,因为它会复制后除外.)
在声明中:
Test t = toto();
Run Code Online (Sandbox Code Playgroud)
,形式语义将让编译器为临时类型Test分配空间,将此空间的地址作为隐藏指针传递toto,然后将此临时复制到t并销毁它.这里的优化包括编译器t直接传递地址
toto,省略中间临时.
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |