当两个用户定义的复制构造函数出现时,有没有办法执行复制构造函数?

时间:2014-02-05 10:22:43

标签: c++ optimization constructor

1= Class_Name( Class_Name& object_name )
2= Class_Name( const Class_Name& object_name )

如果这两个拷贝构造函数都是由用户定义的,那么有没有办法执行no(2)拷贝构造函数(Take copy elision)  考虑的概念)?

2 个答案:

答案 0 :(得分:1)

回答你的问题......复制构造函数no(2)可以执行

#include <iostream>

using namespace std;

class Class_Name
{
  public:
  int xx;

  // Copy Constructor No. 1
  Class_Name(Class_Name& objCopy)
  {
      cout << "Copy Constructor No. 1 called" << endl;
  }

  // Copy Constructor No. 2
  Class_Name(const Class_Name& objCopy)
  {
      cout << "Copy Constructor No. 2 called" << endl;        
  }

  Class_Name(int x) : xx(x) {}  /* conversion constructor */
};


int main()
{    
    Class_Name obj1 = 1; // obj1 is not const, 1 is passed "by value", since it's primitive type
    Class_Name objCopy1 = obj1; // obj1 is not const, other is not const, obj1 is passed by const reference

    const Class_Name obj2 = 2; // obj2 is const
    Class_Name objCopy2 = obj2;

    return 0;
}

输出:

  

复制1号构造函数

     

复制2号构造函数

复制Elision

Class_Name objCopy1 = Class_Name(obj1);

相同
Class_Name objCopy1 = obj1;

答案 1 :(得分:0)

以下是一个例子:

const Class_Name ob1;
Class_Name ob2 = ob1;

这将调用第二版复制构造函数。那是因为你的ob1被定义为常量。我建议你一次阅读维基百科,很好地解释。 http://en.wikipedia.org/wiki/Copy_constructor