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

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

    All things being equal, I pass by const& for sufficiently complex classes, and value for POD and simple objects.

    Laying out the pros/cons to pass by const reference instead of traditional pass by value

    Positives:

    • Avoids a copy (big plus for objects with an expensive copy)
    • Read-only access

    Negatives:

    • Someone can const cast the const off the reference if they really wanted to

    More importantly with the positives is you explicitely control when the copy happens (in your case when passing initializing _b in your initializer list). Thinking about the negatives... I agree it is a risk. I think almost all good programmers will feel dirty about emplying the const_cast. Moreover you can dutifully search for const_cast and throw tomatoes at the person casting the const off the argument. But hey you never know and who has time to watch code like a hawk :)?

    My subjective opinion is that in sufficiently complex classes and in environments where the performance matters the benefit of avoiding the copy constructor outweighs the risk. However for really dumb and POD classes, I tend to make copies of the data and pass by value.

提交回复
热议问题