2

Why there T::T(T&) when there is T::T(const T&) which is more suited for copy?

(Probably it was used to implement move semantic???)

Original description(proven to be wrong by melpomene):

In C++11, a new form of copy constructor T::T(T&) is supported (from cppreferene/Copy constructor Implicitly declared copy constructor) and I wonder what is the practical use of it?

JiaHao Xu
  • 2,452
  • 16
  • 31
  • Somewhat related: https://stackoverflow.com/questions/16956693/why-c-copy-constructor-must-use-const-object – melpomene Sep 29 '18 at 07:46

1 Answers1

5

T(T&) isn't new in C++11. What's new is the use of the default keyword to explicitly define the automatically generated copy constructor:

T(const T &) = default;

As your link says:

A class can have multiple copy constructors, e.g. both T::T(const T&) and T::T(T&). If some user-defined copy constructors are present, the user may still force the generation of the implicitly declared copy constructor with the keyword default.

Before C++11, if you had a T(T&) constructor in your class, it would prevent the automatic creation of T(const T&) (the default copy constructor). Since C++11 you can have both (a user defined T(T&) constructor and an automatic T(const T&) constructor).


As for what a non-const copy constructor is useful for, the answer is "not much". It ensures that only mutable objects can be copied (and not e.g. temporaries), which is not something you usually need.

(Probably it was used to implement move semantic???)

That's exactly right. See e.g. auto_ptr (now removed from the C++ standard), which was similar to unique_ptr before we had move semantics. In particular, it had a auto_ptr(auto_ptr &r) constructor that would modify r (which lead to somewhat unintuitive behavior, which is why it was removed from the language).

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 2
    This doesn't answer the question at all. OP is asking what is use of `T::T(T&)`, not `T::T(const T&)`. – Zereges Sep 29 '18 at 07:35
  • 1
    @Zereges OP's question is based on faulty assumptions (or a misreading of the link). My answer tries to fix that first. – melpomene Sep 29 '18 at 07:37
  • @Zereges Edited. – melpomene Sep 29 '18 at 07:53
  • 1
    Just for completeness, any combination of cv-qualifiers can be applied to the `T&` to form a copy constructor. `T(T&)`, `T(const T&)`, `T(volatile T&)`, and `T(const volatile T&)` are all copy constructors. – Pete Becker Sep 29 '18 at 11:48