Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which constructor is invoked here?

Tags:

c++

c++03

In this code fragment, which constructor is actually called?

Vector v = getVector(); 

Vector has copy constructor, default constructor and assignment operator:

class Vector {
public:
    ...
    Vector();
    Vector(const Vector& other);
    Vector& operator=(const Vector& other);
};

getVector returns by value.

Vector getVector();

Code uses C++03 standard.

Code fragment looks like it is supposed to call default constructor and then assignment operator, but I suspect that this declaration is another form of using copy constructor. Which is correct?

like image 970
SigTerm Avatar asked Mar 31 '12 15:03

SigTerm


1 Answers

When = appears in an initialization, it calls the copy constructor. The general form is not exactly the same as calling the copy constructor directly though. In the statement T a = expr;, what happens is that if expr is of type T, the copy constructor is called. If expr is not of type T, then first an implicit conversion is done, if possible, then the copy constructor is called with that as an argument. If an implicit conversion is not possible, then the code is ill-formed.

Depending upon how getVector() is structured, the copy may be optimized away, and the object that was created inside the function is the same physical object that gets stored in v.

like image 142
Benjamin Lindley Avatar answered Sep 22 '22 23:09

Benjamin Lindley