Pass by value or reference, to a C++ constructor that needs to store a copy?

前端 未结 8 2180
刺人心
刺人心 2020-12-11 19:50

Should a C++ (implicit or explicit) value constructor accept its parameter(s) by value or reference-to-const, when it needs to store a copy of the argument(s) in its object

8条回答
  •  孤城傲影
    2020-12-11 20:24

    In C++98 and C++03, you should pass const& bar and then copy. In C++0x, you should pass bar and then do a move (provided bar has a move constructor).

    #include 
    
    struct foo
    {
        bar _b;
    
        foo(bar b) : _b(std::move(b)) {}
    };
    

    If you construct foo with an lvalue parameter, the copy constructor will be called to create a copy b, and that copy will be moved into _b. If you construct foo with an rvalue parameter, bar's move constructor will be called to move into b, and then it will be moved again into _b.

提交回复
热议问题