How to avoid the copy when I return

后端 未结 3 792
感动是毒
感动是毒 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:08

    I usually work around this by having function signature as

    void foo(set *x)
    

    Just pass it by reference or the other option is already mentioned in the comment.

    Edit: I have changed the argument type to illustrate that x could be changed.

          set s;
          foo(&s);
    

    This is only preferred when you have an old compiler. I suppose that could be the case with some of the projects.

    And, better thing to do will be Either to use move semantics with c++11. Or go ahead returning the container and look into RVO in modern compilers.

提交回复
热议问题