Returning Vectors standard in C++

后端 未结 4 1472
被撕碎了的回忆
被撕碎了的回忆 2021-01-26 12:20

Now, I know this is a common question, but I haven\'t been able to really find a straight answer on this. This is really a question about standards. I am working on a project in

4条回答
  •  既然无缘
    2021-01-26 12:42

    vector func(const vector& input);
    

    All compilers implement RVO either by default or when you turn optimizations on, if you don't turn optimizations on you don't care about performance, so that would not be an issue anyway.

    If your compiler is C++11 conforming, then in the worst case instead of copying 1 pointer you will pay for 3 pointers when move semantics kick in, which compared with the cost of allocating the memory is really no cost.

    Build a simple meaningfull interface, then measure the performance and bottlenecks and optimize from there.

    Depending on your use pattern, if you can reuse the output container, you might want to transform the above into:

    void func(vector& output, const vector& input);
    

    This will have the same performance when creating a new vector, but if you call this function in a loop, you may be able to avoid a few allocations:

    std::vector output;
    for ( ... ) {
       output.clear();
       func(output, input);
    
    // compare with
    for ( ... ) {
       std::vector output = func(input);
    

    In the first block of code, if all of the vectors are of the same size, the clear() will remove the elements but leave the buffer intact, so that the next call to func need not allocate. In the second case it needs to allocate inside func and will deallocate at the end of the scope.

    This is a slightly uglier interface to use, so I would opt for the first one (which semantically is cleaner), and use the second only if the first proves to have an issue with multiple allocations.

提交回复
热议问题