1

我正在尝试了解转换构造函数。我正在使用以下代码

class cls 
{
public:
  cls()
  {
      std::cout << "Regular constructor \n";     ---> Line A
  }
  cls (int a) //Constructing converter
  {
      std::cout << "Int constructor \n";         ---> Line B
  }

  cls (cls& d) //Copy constructor
  {
      std::cout << "Copy constructor \n";        ---> Line C
  }
};


int main()
{
    cls d;
    std::cout << "-----------------------\n";
    cls e = 15; //int constructor then copy constructor
        return;
}

现在我对声明感到困惑,cls e = 15我的理解是该声明假设调用 Line B(Conversion Cont) 然后调用 Line C (Copy constructor) 但是它只调用 Line B. 我虽然cls e = 15相当于cls e = cls(15). 所以我尝试cls e = cls(15)了它也只给出了 B 行。如果有人能解释当我们使用以下内容时会发生什么,我将不胜感激

cls e = cls(15)//我期待一个转换构造函数,然后是复制构造函数,但显然我错了。任何关于正在发生的事情的解释将不胜感激

4

3 回答 3

3

This is due to copy elision compiler optimization. An compiler is allowed to elide copy constructor calls in certain cases. What you see is this optimization in action. You are right in assuming calls to:

  • Conversion constructor and then a
  • Copy constructor

But in this case the second call is elided/removed/optimized by the constructor by using return value optimization. The compiler constructs the object directly in to e rather than creating a temporary object and then copying it to e.

If you are using GCC you can use -fno-elide-constructors option to disable copy-elision and you should see the result you expected.

于 2013-08-25T13:57:22.260 回答
0

It seems that the compiler is optimising your code not ot call the copy constructor which is known as copy elision

Please look HERE for more details.

Basically in copy elision a compiler optimizez your code to omit unnessesary intermediate temporary objects.

于 2013-08-25T13:58:01.930 回答
0

You are right about that cls e = 15 is the same as cls e = cls(15). This is because your cls(int a) is not declared explicit. Next is just compiler copy elision optimization.

于 2013-08-25T13:59:48.293 回答