未在模板中调用复制构造函数 class
copy constructor not called in template class
#include <iostream>
using namespace std;
template <typename T> class tt
{
public :
int data;
tt()
{
std::cout << std::endl << " CONSTRUCTOR" << std::endl;
}
tt(const tt & that)
{
std::cout << std::endl << " COPY CONSTRUCTOR" << std::endl;
}
};
tt<int> test(void)
{
std::cout << std::endl << " INSIDE " << std::endl; tt<int> a; a.data =10 ;return a;
}
int main() {
// your code goes her
//tt<int> b;
tt<int> a =test();
cout<<a.data; //so that return value optimisation doesn't take place
return 0;
}
为什么在这种情况下没有调用复制构造函数?
虽然在以下情况下会被调用
tt<int> b;
tt<int> a =b;
代码 link : http://ideone.com/e9lq3C
编辑:这不是 What are copy elision and return value optimization? 的副本,因为在代码中引用了返回值。
这都是编译器优化造成的(至少RVO)。编译器最终只为她创建了一个对象(您要求在 test()
中本地创建的对象成为与您的 a
变量相同的对象)。
a
与临时文件没有不同的位置。这就是复制省略和 return 值优化所做的……它们使您不会得到临时的。你在 test()
中说 a
的地方,优化意味着你指的是与 main
中的 a
相同的位置。所以不需要复制。
#include <iostream>
using namespace std;
template <typename T> class tt
{
public :
int data;
tt()
{
std::cout << std::endl << " CONSTRUCTOR" << std::endl;
}
tt(const tt & that)
{
std::cout << std::endl << " COPY CONSTRUCTOR" << std::endl;
}
};
tt<int> test(void)
{
std::cout << std::endl << " INSIDE " << std::endl; tt<int> a; a.data =10 ;return a;
}
int main() {
// your code goes her
//tt<int> b;
tt<int> a =test();
cout<<a.data; //so that return value optimisation doesn't take place
return 0;
}
为什么在这种情况下没有调用复制构造函数?
虽然在以下情况下会被调用
tt<int> b;
tt<int> a =b;
代码 link : http://ideone.com/e9lq3C
编辑:这不是 What are copy elision and return value optimization? 的副本,因为在代码中引用了返回值。
这都是编译器优化造成的(至少RVO)。编译器最终只为她创建了一个对象(您要求在 test()
中本地创建的对象成为与您的 a
变量相同的对象)。
a
与临时文件没有不同的位置。这就是复制省略和 return 值优化所做的……它们使您不会得到临时的。你在 test()
中说 a
的地方,优化意味着你指的是与 main
中的 a
相同的位置。所以不需要复制。