1

I came across this example from Accelerated C++

vector<string> func(const string&); //function declaration

vector<string> v;
string line = "abc";

v = func(line); //on entry, initialization of func's single parameter from line
         //on exit, both initialization of the return value and then assignment to v

My question is, since func takes a const string reference as a parameter, why is the copy constructor invoked when entering func? Since line is being passed by reference doesn't func just keep a reference to line on its local stack?

Jeff
  • 79
  • 6
  • 1
    What makes you think that the copy constructor is invoked? – Kerrek SB Oct 06 '11 at 23:22
  • This is what the book implies with the comment "on entry, initialization of func's parameter from line" – Jeff Oct 06 '11 at 23:23
  • 1
    I cannot see the funct body - are you adding that string to vector? stl containers have pass-by-value semantics – alexm Oct 06 '11 at 23:23

2 Answers2

5

on entry, initialization of func's single parameter from line

func's parameter is initialized from line, but it's not a string, but a reference to it. Its initialization do not result in a call to the copy constructor, but it makes the parameter become an alias for line (as always happens with initialization of references).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
1

That example is not quite right. As you already noticed, the function argument is passed by const reference, and there are no conversions involved, so there is no copy constructor involved with it. The result, on the other hand, could be invoking a copy constructor from the return value to the vector v, depending on how is your function declared. Nowadays most compilers implement RVO and NRVO, which are allowed standard optimizations that elude that copy construction. Read more about that here:

http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

K-ballo
  • 80,396
  • 20
  • 159
  • 169