【问题标题】:copy constructor not called in template class [duplicate]模板类中未调用复制构造函数[重复]
【发布时间】: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;

代码链接:http://ideone.com/e9lq3C

编辑:这不是 What are copy elision and return value optimization? 的重复,因为返回的值在代码中被引用。

【问题讨论】:

  • @πάντα ῥεῖ 请查看编辑,为什么不重复
  • 为什么你认为代码中引用的返回值会影响这个?
  • @JBB 为什么不呢? a 在内存中的位置与test() 返回的临时tt&lt;int&gt; 不同。所以如果我们引用a的内存位置,那么首先需要构造它,在这种情况下是复制构造。
  • @q126y 不,它没有,打印指针并查看。这就是 RVO 的重点,您在调用函数的堆栈中构造对象以避免复制它。
  • 这个重复的。

标签: c++ templates copy-constructor


【解决方案1】:

a 没有与临时位置不同的位置。这就是复制省略和返回值优化所做的......他们这样做是为了让你不会得到一个临时的。你在test() 中说a,优化意味着你指的是与main 中的a 相同的位置。所以不需要副本。

【讨论】:

    【解决方案2】:

    这一切都归功于编译器优化(至少RVO)。编译器最终只为她创建了一个对象(您要求在 test() 本地创建的对象与您的 a 变量成为同一个对象)。

    【讨论】:

      猜你喜欢
      • 2015-09-30
      • 1970-01-01
      • 2012-02-06
      • 2016-03-22
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多