开发者

Rvalue reference

开发者 https://www.devze.com 2023-01-14 17:37 出处:网络
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

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?


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;
}
0

精彩评论

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

关注公众号