Why is the copy constructor not called?

后端 未结 4 1371
醉酒成梦
醉酒成梦 2020-11-28 12:13
class MyClass
{
public:
  ~MyClass() {}
  MyClass():x(0), y(0){} //default constructor
  MyClass(int X, int Y):x(X), y(Y){} //user-defined constructor
  MyClass(cons         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 12:44

    Apart from what Potatoswatter and Andrey T. has said, note that you can coax most compilers not to elide constructors. GCC typically provides you with -fno-elide-constructors and MSVC with /Od which should give you the desired output. Here's some code:

    #include 
    
    #define LOG() std::cout << __PRETTY_FUNCTION__ << std::endl // change to __FUNCSIG__ on MSVC > 2003
    
    class MyClass
    {
    public:
      ~MyClass() { LOG(); }
      MyClass():x(0), y(0){LOG(); } //default constructor
      MyClass(int X, int Y):x(X), y(Y){LOG(); } //user-defined constructor
      MyClass(const MyClass& tempObj):x(tempObj.x), y(tempObj.y){LOG(); } //copy constructor
    
    private:
    int x; int y;
    };
    
    int main()
    {
     MyClass MyObj(MyClass(1, 2)); //User-defined constructor was called.
     MyClass MyObj2(MyObj); //Copy constructor was called.
    }
    

    Compiled with GCC 4.5.0 on MingW32:

     g++ -Wall -pedantic -ansi -pedantic tmp.cpp -o tmp -fno-elide-constructors
    

    Output:

    $ tmp.exe
    MyClass::MyClass(int, int)
    MyClass::MyClass(const MyClass&)
    MyClass::~MyClass()
    MyClass::MyClass(const MyClass&)
    MyClass::~MyClass()
    MyClass::~MyClass()
    

提交回复
热议问题