Can't the constructor be called when creating a temporary object with a return value?

Asked 2 years ago, Updated 2 years ago, 163 views

#include <iostream>

class Point
{
    int x, y;
public:
    Point (int a = 0, int b = 0): x(a), y(b) {std::cout << "execute creator"<< std::endl;}
    friend Point operator+(const Point& p1, const Point& p2);
};

Point operator+(const Point& p1, const Point& p2)
{
    return Point(p1.x+p2.x, p1.y+p2.y);
}

int main()
{
    Point(1,1);
    Point p1(1,1);
    Point p2(2,2);
    Point p3 = p1+p1;
}

Running a function

I thought there were a total of five "execute the creator" posts, but only four...

When the first line of the main function is cleared, a total of three "execute constructor" statements appear, so I don't think the constructor was called in the temporary object generated as a return value in the +operator, is that right? Can an object be created without a constructor?

c++ rvo class temporary-object

2022-09-22 19:44

1 Answers

It's too late to help

Because a temporary object was created in 4

In my case, I need to work on the operator =. The college admissions operator is activated.


2022-09-22 19:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.