C++ universal reference in constructor and return value optimization (rvo)
Asked Answered
H

1

9

Why does rvalue optimization not occur in classes with constructor with universal reference arguments?

http://coliru.stacked-crooked.com/a/672f10c129fe29a0

#include <iostream>

 template<class ...ArgsIn>
struct C {

  template<class ...Args>
  C(Args&& ... args) {std::cout << "Ctr\n";}        // rvo occurs without &&

  ~C(){std::cout << "Dstr\n";}
};

template<class ...Args> 
auto f(Args ... args) {
    int i = 1;
  return C<>(i, i, i);
}

int main() {
  auto obj = f();
}

Output:

Ctr
Ctr
Dstr
Ctr
Dstr
Dstr
Headpiece answered 24/7, 2014 at 4:27 Comment(14)
Universal reference is a term coined by one particular author and with which other people disagree… I personally believe that it causes more confusion than it helps, you should try to understand how type deduction works, as this is the answer to the question here.Ahimsa
using g++ 4.8.3 I get Ctr Dstr for both C(Args... args) and C(Args &&... args) . What is your compiler and version (and flags)?Flinger
@MattMcNabb "g++ -std=c++1y -O3 -Winline -Wextra -pthread -pedantic-errors" version 4.9. GCC 4.8.1 also not do rvo coliru.stacked-crooked.com/a/d2ddb81f9ed2d217Headpiece
is auto f() legal without specifying -> type ?Flinger
… actually I don't think that type deduction has much to do here… the compiler is not doing an optimization (which as all optimizations is not mandatory) and is opting to use a move-constructor (generated out of the variadic args constructor) instead of eliding the copy altogether. Small tweaks to the source make RVO kick in or fail (for example, providing a move constructor yourself makes RVO kick in (?!?!)…Ahimsa
@MattMcNabb: auto f() { is (will be) legal C++14, and some compilers already support it.Ahimsa
@DavidRodriguez enabling cout for move constructor, I still only get Ctr Dstr for both versions. (adding in -fno-elide-constructors gets Ctr move Dstr move Dstr Dstr)Flinger
@MattMcNabb Yes, sure. Since C++1y. But you can replace it with concrete type. It does not change anything.Headpiece
It seems dependent on whether you have a move constructor overload.Fourwheeler
@Fourwheeler Nice. But WHYY???Headpiece
@DavidRodríguez-dribeas When I add move constructor coliru.stacked-crooked.com/a/16eece557520213e, compiler not call it due to this https://mcmap.net/q/1315240/-is-rvo-return-value-optimization-on-unnamed-objects-a-universally-guaranteed-behavior ?Headpiece
What is "rvalue optimization"?Schaffel
@tower120: That link explains what RVO is, but doesn't explain why the compipler can't call itLeftwich
@MooingDuck That was the question, not explanation.Headpiece
F
12

I believe that the problem is that instantiations of

template<class ...Args>
C(Args&& ... args) {std::cout << "Ctr\n";}  

are not copy/move constructors as far as the language is concerned and therefore calls to them cannot be elided by the compiler. From §12.8 [class.copy]/p2-3, emphasis added and examples omitted:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

A non-template constructor for class X is a move constructor if its first parameter is of type X&&, const X&&, volatile X&&, or const volatile X&&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

In other words, a constructor that is a template can never be a copy or move constructor.

The return value optimization is a special case of copy elision, which is described as (§12.8 [class.copy]/p31):

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects.

This allows implementations to elide "copy/move construction"; constructing an object using something that's neither a copy constructor nor a move constructor is not "copy/move construction".

Because C has a user-defined destructor, an implicit move constructor is not generated. Thus, overload resolution will select the templated constructor with Args deduced as C, which is a better match than the implicit copy constructor for rvalues. However, the compiler can't elide calls to this constructor, as it has side effects and is neither a copy constructor nor a move constructor.

If the templated constructor is instead

template<class ...Args>
C(Args ... args) {std::cout << "Ctr\n";} 

Then it can't be instantiated with Args = C to produce a copy constructor, as that would lead to infinite recursion. There's a special rule in the standard prohibiting such constructors and instantiations (§12.8 [class.copy]/p6):

A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv-qualified) X and either there are no other parameters or else all other parameters have default arguments. A member function template is never instantiated to produce such a constructor signature.

Thus, in that case, the only viable constructor would be the implicitly defined copy constructor, and calls to that constructor can be elided.

If we instead remove the custom destructor from C, and add another class to track when C's destructor is called instead:

struct D {
    ~D() { std::cout << "D's Dstr\n"; }
};

template<class ...ArgsIn>
struct C {
  template<class ...Args>
  C(Args&& ... args) {std::cout << "Ctr\n";}
  D d;
};

We see only one call to D's destructor, indicating that only one C object is constructed. Here C's move constructor is implicitly generated and selected by overload resolution, and you see RVO kick in again.

Fourwheeler answered 24/7, 2014 at 4:59 Comment(14)
Can you explain how this relates to the problem?Flinger
@MattMcNabb RVO elides copy/move constructor calls. It doesn't (apparently) elide calls to something that's neither.Fourwheeler
OK, so the issue is arising because Args is being deduced as CFlinger
@MattMcNabb Right, and it becomes something that seems like a move constructor but really isn't.Fourwheeler
@Fourwheeler So, you think this is some kind of a compiler bug?Headpiece
@Headpiece No, it's not a compiler bug. This is the behavior specified by the standard. The compiler is not allowed to elide calls to the templated constructor, because it's neither a copy constructor nor a move constructor.Fourwheeler
@Fourwheeler Here §12.8 [class.copy]/p2-3 said about NON-TEMPLATE constructor. Which is not our case.Headpiece
@Headpiece The only kind of constructors that can be copy/move constructors is non-template constructors.Fourwheeler
@Fourwheeler You said that compiler is not allowed to elide call to constructor, because it's not copy/move ctr. But I not say about copy elision. I talk about en.wikipedia.org/wiki/Return_value_optimization . So what we have? We have a single constructor and destructor. And none of copy/move constructors. So what prevents compiler from this form of optimization?Headpiece
@Headpiece Return value optimization is copy elision. That's how it's specified - as the compiler being allowed to elide certain copy/move operations.Fourwheeler
+1, great answer. I said basically the same thing when closing the bug report as INVALID: gcc.gnu.org/bugzilla/show_bug.cgi?id=61892#c1Needlefish
@JonathanWakely The only thing that I understand from all of this - is that it can't be done, because Args can be C, and that can start infinite recursion :)Headpiece
Well then you've understood completely wrong. Declare copy and move constructors and you get RVO in all allowed situations, or constrain the constructor template using SFINAE so it cannot be used to copy or move C objects.Needlefish
@JonathanWakely Can you show simple example of that thing with SFINAE? :)Headpiece

© 2022 - 2024 — McMap. All rights reserved.