c++ - Copy constructor invoked 2 times, not 3 as expected? -
here 1 program taken textbook featuring copy constructors:
#include <stdio.h> #include <conio.h> #include <iostream> using namespace std; class point { private: int x,y; public: point(int ox =0, int oy =0) { cout << " make object" << << endl; cout << " using default constructor \n"; x = ox, y = oy; } point(const point &p) { cout << " make object" << << endl; cout << " using copy constructor \n"; x = p.x, y = p.y; } void move(int dx, int dy); void display(); }; point fct(point a); int main() { point a(5,2); a.display(); point b = fct (a); b.display(); getch(); return 0; } void point::move(int dx, int dy) { x += dx, y += dy; } void point::display() { cout << "coordinates :" << x << " " << y << "\n"; } point fct(point a) { point b=a; //b.move(2,3); return b; }
it should noted copy constructor of form : point (const point &p) instead of point (point &p) (the latter what's in textbook, couldn't compile had switch first one, still can't understand why :( )
the textbook said there 3 lines of "using copy constructor" , corresponding 3 calls copy constructor. think reason is, when call: b = fct(a)
the function "fct" makes copy of (pass-by-value), therefor 1 call
the line : point b = : again, copy constructor invoked
the return value copied b (the variable in main, not 1 in fct) 3rd one.
however upon execution, there 2 calls. can give me explaination on this?
two copies occur because named return value optimization (nrvo) elides 1 of copies.
point fct(point a) { point b=a; return b; } point b = fct (a);
the first copy 1 argument a
in main
parameter a
in fct
. occurs because point
taken by-value.
the second copy a
b
inside func.
the copy elided 1 in returning b
value. in case, b
can directly allocated b
@ call site, no copy takes place.
Comments
Post a Comment