开发者

Why is the copy constructor called on a function argument when the argument is passed by reference?

I came across this example from Accelerated C++

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

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

v = func(line)开发者_如何学Python; //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?


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).


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/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜