Why C++ copy constructor must use const object?

后端 未结 8 1660
夕颜
夕颜 2020-11-30 02:18

I understand that when we define a class copy constructor of the class is necessary as Rule of three states. I also notice that the argument of the copy constructor is usual

相关标签:
8条回答
  • 2020-11-30 02:48
    • Logically, it should make no sense to modify an object of which you just want to make a copy, though sometimes it may have some sense, like a situation where you'd like to store the number of time this object has been copied. But this could work with a mutable member variable that stores this information, and can be modified even for a const object (and the second point will justify this approach)

    • You would like to be able to create copy of const objects. But if you're not passing your argument with a const qualifier, then you can't create copies of const objects...

    • You couldn't create copies from temporary reference, because temporary objects are rvalue, and can't be bound to reference to non-const. For a more detailed explanation, I suggest Herb Sutter's article on the matter

    0 讨论(0)
  • 2020-11-30 02:55

    The last thing any consumer of your class would expect is a copy constructor that changed the object that was copied! Therefore, you should always mark as const.

    0 讨论(0)
提交回复
热议问题