copy constructor is not called?

↘锁芯ラ 提交于 2019-12-25 09:29:42

问题


class X
{
  int i;  
  public:
  X(int m) : i(m) {};

  X(const X& x)
  {
    //cout "copy constructor is called\n";
  }

  const X opearator++(X& a,int)
  {
     //cout "X++ is called\n";
     X b(a.i);
     a.i++;
     return b;
  }
  void f(X a)
  {   }
};

 int main()
{ 
  X a(1);
  f(a);
  a++; 
  return 0;
}

Here when function 'f' is called copy constructor is getting called as expected. In case of a++, operator++ function is called but when it returns "copy constructor is not called". why "copy contructor is not called while returning from function 'operator++'?


回答1:


I believe you've encountered return value optimization (RVO) http://en.wikipedia.org/wiki/Return_value_optimization




回答2:


The web-wide famous C++ FAQ Lite (which you can find here for instance) is a must-read for every C++ programmer.

Your question probably corresponds to that one :
[10.9] Does return-by-value mean extra copies and extra overhead?




回答3:


The compiler is permitted to elide the call to a copy constructor when an object is returned from a function.

That is, it is not required to actually call the copy constructor: it can just construct the object to be returned in whatever place the object needs to be to be returned from the function.




回答4:


It looks like RVO (Return Value Optimization). Your compiler sees that you are not doing anything with the 'b' instance nor with its returned copy so it removes it (object copy operation) from the compiled output.




回答5:


It's legal to ellide copies, even when the copy constructor has side effects. It's called RVO (there's also one for named (comment: thanks) values, NRVO) and is explicitly allowed by the Standard.




回答6:


Well, you had several errors in your code. If you compile and run the code i've attached you'll see the copy contructor is successfully called when operator++ returns.

#include <iostream>

class X {
public:
    X(int m) : i(m) {};

    X(const X& x)
    {
        std::cout << "Copy constructor is called\n";
    }

    X
    operator++(int)
    {
        std::cout << "X++ is called\n";

        this->i++;
        return *this;
    }


private:
    int i;

};


void
f(X a)
{
}


int
main(void)
{
    X a(1);
    f(a);
    a++;
    return 0;
}


来源:https://stackoverflow.com/questions/3084753/copy-constructor-is-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!