How to avoid the copy when I return

后端 未结 3 788
感动是毒
感动是毒 2021-01-18 00:28

I have a function which returns a vector or set:

set foo() {
    set bar;
    // create and massage bar
    return bar;
}

set

        
3条回答
  •  生来不讨喜
    2021-01-18 01:10

    Check out return value optimization. A modern compiler will optimize this situation, and in straightforward situations like these, no copy will be made on any of the major compilers.

    In principle, you could also create your object outside the function, and then call the function and pass the object to it by reference. That would be the old way of avoiding a copy, but it is unnecessary and undesirable now.

提交回复
热议问题