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

前端 未结 8 2194
刺人心
刺人心 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:33

    I'm assuming bar has a normal copy constructor of the form bar(const bar &b)

    Take a const reference here. bar's constructor will then take that reference, and perform the copy. Total copies: 1.

    If you left the reference off, the compiler would make a copy of b, pass the copy to foo's constructor, which would then pass it to bar and copy that.

提交回复
热议问题