While trying to understand Rvalue references from here, I am unable to understand two things
- 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?
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;
}
精彩评论