views:

55

answers:

1
+1  Q: 

Rvalue reference

While trying to understand Rvalue references from here, I am unable to understand two things

  1. If there are N strings in the vector, each copy could require as many as N+1 memory allocations and [...]

What is this +1 in 'N+1'?

2.How the author suddenly arrives at the below guideline

Guideline: Don’t copy your function arguments. Instead, pass them by value and let the compiler do the copying.

Am I missing something?

+3  A: 

What is this +1 in 'N+1'?

One allocation to create the underlying array for the new vector, then N allocations, one for each of the N strings in the vector.

How the author suddenly arrives at the below guideline

He is arguing that instead of explicitly making the copy inside of the function,

std::vector<std::string> 
sorted2(std::vector<std::string> const& names) // names passed by reference
{
    std::vector<std::string> r(names);         // and explicitly copied
    std::sort(r);
    return r;
}

you should let the compiler make the copy when you pass the arguments to the function,

std::vector<std::string> 
sorted2(std::vector<std::string> names)        // names passed by value
{                                              // and implicitly copied
    std::sort(names);
    return names;
}
James McNellis
@James McNellis: Oh. The advantage is that when 'call by value' semantics is used, there is a possibility of copy elision, which is not there in case 'call by reference' semantics is used. Is that right?
Chubsdad
This has also been pointed out by Meyers -- how often we end up copying manually when we should've just let the compiler do the copy for us.
dirkgently
@chubsdad: Yes.
James McNellis
@dirkgently: Any reference to Scott's articles?
Chubsdad
Effective C++, Item 19: Understand the origin of temporary objects.
dirkgently