【发布时间】:2016-04-13 02:43:30
【问题描述】:
#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;
编辑:这不是 What are copy elision and return value optimization? 的重复,因为返回的值在代码中被引用。
【问题讨论】:
-
@πάντα ῥεῖ 请查看编辑,为什么不重复
-
为什么你认为代码中引用的返回值会影响这个?
-
@JBB 为什么不呢?
a在内存中的位置与test()返回的临时tt<int>不同。所以如果我们引用a的内存位置,那么首先需要构造它,在这种情况下是复制构造。 -
@q126y 不,它没有,打印指针并查看。这就是 RVO 的重点,您在调用函数的堆栈中构造对象以避免复制它。
-
这个是重复的。
标签: c++ templates copy-constructor