Why C++ copy constructor must use const object?

后端 未结 8 1681
夕颜
夕颜 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:33

    It's not a "must" in technical sense. We even have such beast right in the standard, though it got deprecated. Follow the links for the reasoning.

    The semantics of copy we expect is to leave the "template" unchanged and provide a clone that is an exact equivalent in all regards, that you have hard time to tell form original.

    That being expected you shall think twice to have a copy ctor that does otherwise. It will surprise users and likely introduce bugs. And frustration and noise, just try to google for 'vector of auto_ptr' just to see the count.

    The remainder of the question could be "I swear not to touch the original in implementation, but want a different signature". What signature then? Let's try T and T&.

    T drops out as it would require copy ctor to be usable and we're implementing just that. Recursion: see recursion.

    That leaves T&. That would actually work for a deal of cases. But just fail if your original object happens to sit around in a const form, or be temporary. Why hinder that sensible case for no rain at all?

提交回复
热议问题