开发者

c++ implicit copy constructor and the assignment operator

开发者 https://www.devze.com 2023-02-23 14:17 出处:网络
I have a class defined as follows: #include <iostream> using namespace std; class Point { int x, y; public:

I have a class defined as follows:

#include <iostream>

using namespace std;

class Point
{
    int x, y;

public:

    Point(int a, int b) : x(a), y(b)
    { 
        std::cout << "Constructing point ( " << a << ", " << b << " ) " 
                 << std::endl;
    }

    Point(const Point& p) : x(p.x), y(p.y)
    {
        std::cout << "In copy constructor " << p.x << " " << p.y 
      开发者_StackOverflow中文版           << std::endl;
    }

    Point& operator=(const Point& p)
    {
        std::cout << "In assignment operator " << p.x << " " << p.y 
                 << std::endl;
        x = p.x;
        y = p.y;
        return *this;
    }
};

int main()
{
    Point p1 = Point(1, 2); 

    return 0;
}

Now when I execute this all I see is Constructing point (1, 2). I am assuming that the compiler is doing some optimization here. Is it correct that in theory a temporary gets constructed and then the assignment operator is called to initialize p1?


No, in a declaration like that the = operator actually still means to call a constructor, and the compiler probably elided away any possible copy construction as an optimization. = in a declaration would never result in an assignment being called. So in theory a temporary could be created and copy-constructed into p1.


If you want see the operator = called, you must write a code like this:

Point p1(5, 5);
Point p2(0, 0); //You don't have a default constructor.

p2 = p1; // Now operator = is called.
0

精彩评论

暂无评论...
验证码 换一张
取 消