Does RVO optimisation happens when a copy constructor is not defined for a class?

StackOverflow https://stackoverflow.com/questions/21824689

  •  12-10-2022
  •  | 
  •  

Frage

Lets say I have this piece of code:

class Base {
public:
    void f() {}
private:
    int n;
};

Base foo()
{
    Base b;

    // processing

    return b;
}

Base doesn't have a copy constructor defined and looking at its members the compiler won't synthesise one.
Is Named Return Value (NRV) optimisation applied for this code ? What is the exact rule when a compiler would apply NRV ?

War es hilfreich?

Lösung

First of all, there's no exact rule, because NRVO is not explicitly part of the standard, but rather is allowed by other parts of the standard. The compiler is never required to employ NRVO, and different compilers will be inhibited from using NRVO by different constructs.

In your situation, there's nothing obvious to inhibit the use of NRVO. There's no explicit destructor or copy constructor, and the returned variable is declared outside any conditional or loop block. It depends on what's going on in that // processing area, though.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top