How to avoid the copy when I return

后端 未结 3 791
感动是毒
感动是毒 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 00:56

    Modem C++ compiler will implement: given a type T:

    • If T has an accessible copy or move constructor, the compiler may choose to elide the copy. This is the so-called (named) return value optimization (RVO), which was specified even before C++11 and is supported by most compilers.
    • Otherwise, if T has a move constructor, T is moved(Since C++11).
    • Otherwise, if T has a copy constructor, T is copied.
    • Otherwise, a compile-time error is emitted.

提交回复
热议问题