The C ++ project states:
12.8p31 This permission of copy / move operations, called copying, is allowed in the following cases (which can be combined to eliminate multiple copies):
(...)
- when a temporary class object that was not attached to a link (12.2) is copied / moved to a class object with the same cv-unqualified type, the copy / move operation can be omitted from building the temporary object directly to the target of the missed copy / move
In other words:
X MakeX() { return X(); // Copy elided } X MakeX() { const X& x = X(); // Copy not elided return x; }
What is the reason for this limitation for links ?
Please do not focus on the reliability of the following examples, as they simply illustrate that I do not see the difference (IMHO) between the temporary and the link.
On the one hand, by introducing the link, we allowed the other peers to use the same object, and the calling MakeX() object expected it to be safe and clean.
class Y { public: Y(const X& x) : _xRef(x) {} private: const X& _xRef; }; X MakeX() { const X& x = X(); Y y{x}; StaticStuff::send(y); return x;
But what about this case (maybe it's UB;)):
class Y { public: Y(X* x) : _xPtr(x) {} private: X* _xRef; }; X MakeX() { X x; Y y{&x};
source share