Named Return Value Optimization (NRVO) from the compilers' perspective
Copy Elision
Copy Elision is a general term for optimizations that remove unnecessary copies. A few of the simplest cases of Copy Elision:
T t = T();
In that case, we could expect the object T to be created with a default constructor and then copied using operator=.
But, in reality, we get just one default constructor call.
T t = T(T(T(T(T(T(T(T(T(1)))))))));
Here, we could expect one call to T(1), many calls to T(const T&), and an operator= call.
But instead we get only T(1).
We basically remove unnecessary work.
So what is Copy Elision formally speaking?
According to [class.copy.elision]:
When certain criteria are met, an implementation is allowed to omit the creation of a class object from a source object of the same type (ignoring cv-qualification), even if the selected constructor and/or the destructor for the object have side effects.
In the C++ Standard, there are 4 cases in which Copy Elision takes place:
- In a
returnstatement. - In a
throwexpression. - In a coroutine.
- In exception-declarations (
catchblocks).
We’re interested in the first case.
Here, we’ll start with Unnamed Return Value Optimization (URVO, or more often just RVO) and then look at the Named version of RVO.
Return Value Optimization (RVO)
Let’s look more closely at that first case about return statements:
in a return statement ([stmt.return]) in a function with a class return type, when the expression is the name of a non-volatile object o with automatic storage duration (…), the copy-initialization of the result object can be omitted by constructing o directly into the function call’s result object;
So RVO is a special case of Copy Elision that applies only to prvalues in return statements.
Since C++17, RVO is a mandatory optimization.
Let’s explore a few examples of RVO. To do that, we will use a helper struct that will tell us what operations were performed:
#define TELL (str) { std::cout << str << std::endl; }
struct S {
S() TELL("def")
S(const S&) TELL("cp")
S(S&&) TELL("mv")
S(std::string&&) TELL("str&&")
int x = 0;
};
Let’s check some basic cases:
S f1() { return S(); }
const volatile S f2() { return S(); }
int main() {
S s1 = f1(); // def
S s2 = f2(); // def
}
Here, RVO works.
That’s our main observation.
And const volatile modifiers don’t break it.
Sometimes you construct your object implicitly:
S f() {
return std::string(10, '1');
}
int main() {
S s = f(); // str&&
}
You can actually think of that code as:
S f() {
return S(std::string(10, '1'));
}
And in that case, you’re in the same situation as in the previous cases.
But of course, we don’t write code like that. I mean, usually, you have at least some logic:
S f(bool flag) {
if (flag) {
return S();
}
return std::string(10, '1');
}
Will such code break our optimization?
No!
Since RVO works in terms of every return separately,
all other return statements don’t affect one certain return.
Nice!
What if you move your object instead of just returning it?
S f() {
return std::move(S());
}
The problem here is that the compiler is obliged to create the object S to pass it to std::move.
So, by using std::move incorrectly, you could break RVO and make your code less performant.
I’ve seen an overly broad interpretation of the rule «no std::move in return statements»:
std::pair<S, S> f() {
S s1;
S s2;
return {s1, s2};
}
Of course, you get copies of s1 and s2 here.
You should actually move both objects into the std::pair to replace the copies with moves.
Okay. Seems like RVO is pretty straightforward. Right?
Named Return Value Optimization (NRVO)
As you might expect, it happens when we have a named variable. Here is an example:
S f() {
S s;
return s;
}
// S s = f();
// def
So we create an object and then return it. Yet we get only a call to the default constructor!
Of course, we don’t write code like that. We do some actual work!
S f() {
S s;
if (rand() % 2 == 1) { s.x = 1; }
else { modify(s); }
return s;
}
// S s = f();
// def
It still works!
So how does it work?
Here we need to learn one term: return slot. The return slot of a function is a place in memory where we store the function’s result.
NRVO works as follows:
- check whether the conditions for NRVO are met
- if everything is fine, create your NRVO variable in the return slot.
That means that, for NRVO to succeed, the allocation of the variable being returned should be controlled by the function itself. So function parameters, static variables, global variables, and so on don’t satisfy the conditions for NRVO.
So the function doesn’t actually need to allocate memory on its stack. It could work directly with the memory of the parent function. From this physical understanding of NRVO, we can derive an important condition for the optimization to be possible: the function’s return type should be the same as the type of the variable in which we store the result.
Why is that important? Suppose NRVO works in the following example:
B f() {
B b;
return b;
}
int main() {
A a = f();
}
In that case, where the return type is not the same as the result type, we would be working with the address
of an object of type A as if it were memory for an object of type B.
And that’s a violation of the strict aliasing rule.
So NRVO would not be possible in such situations.
Let’s check how NRVO and std::move go together:
S f() {
S s; // def
return std::move(s); // mv
}
Here, we no longer have the name of a local variable in the return statement, as we were supposed to, but rather an expression.
And it breaks NRVO!
The thing is, our compilers are smart enough to move variables by themselves if that’s possible. The chain of reasoning is as follows:
- Could I do NRVO for that variable? If yes, do it. If no, go to 2.
- Could I move that variable? If yes, do it. If not, go to 3.
- Could I copy that variable? If yes, do it. If not, go to 4.
- COMPILER ERROR!!!!!
By using explicit std::move in a return statement, we remove the first step from that chain.
Not good.
There are a few other cases when our optimization doesn’t work. For instance, when we can’t control a variable’s location in memory:
static S x;
S f() { return x; }
Or with structured bindings:
struct Compose { S s; int i; };
Compose Get() { return {S(), 1}; } // def
S f() {
auto [s, i] = Get();
return s; // cp
}
f() code is eventually equivalent to:
S f() {
Compose __c = Get();
S s = __c.s;
int i = __c.i;
return s;
}
The problem here is that s is actually a part of a bigger type.
And in order to make NRVO happen, we need to create s in one place in memory (the return slot),
but i should be created in another.
Object layout doesn’t work like this in C++, so NRVO here is not possible.
If you remember, NRVO is not a mandatory optimization. Compilers just do it because they care about the performance of our code. But they do it in their own ways, and you can’t always be confident what happens.
Also, since you can’t rely on that optimization happening, you are still bound by the need to have a move constructor:
struct NonMovable {
NonMovable() = default;
NonMovable(const NonMovable&) = default;
NonMovable(NonMovable&&) = delete;
};
If NRVO were possible for a NonMovable object in some function, we would still get a compilation error.
Yes, of course, we don’t need to use a move constructor.
And the compiler could create the object successfully.
But if the logic of that optimization changes at some point, we will find ourselves in a situation where
our code is broken.
So compilers prefer not to allow that to happen.
We will explore how NRVO works in the main compilers today, but keep in mind that the implementation of that optimization could change someday. And all the text below could later be irrelevant.
To be honest, it would be a great thing for me to learn that this article is already completely outdated. That means that things got much better.
Clang
First of all, we need to understand that NRVO today is an optimization which happens at the semantic analysis level. However, that doesn’t mean that if NRVO didn’t happen at that step, the compiler wouldn’t be smart enough to optimize the code later.
If the conditions for NRVO are met, Clang marks the AST node for that variable with the nrvo label.
How could you check that?
Open godbolt.org. Choose Clang (trunk, for instance). Insert your example. I used this one:
struct S {};
S f() {
S s;
return s;
}
int main() {}
Choose AST:

And in the AST representation of your code, find the line corresponding to the variable declaration. In my case, it looks like this:
| | `-VarDecl <col:5, col:7> col:7 used s 'S' nrvo callinit
Do you see the nrvo label here?
Great.
Let’s explore how NRVO works in Clang in more depth. We will use that example:
S f(bool b) {
S y;
if (b) {
S s;
return s; // ?
}
return y; // ?
}
While parsing, Clang holds a «tree» of all the scopes in the program.
Deep inside
Scope is represented as follows:
class Scope {
...
/// A single NRVO candidate variable in this scope.
/// There are three possible values:
/// 1) pointer to VarDecl that denotes NRVO candidate itself.
/// 2) nullptr value means that NRVO is not allowed in this scope
/// (e.g. return a function parameter).
/// 3) std::nullopt value means that there is no NRVO candidate in this scope
/// (i.e. there are no return statements in this scope).
std::optional<VarDecl*> NRVO;
/// Represents return slots for NRVO candidates in the current scope.
/// If a variable is present in this set, it means that a return slot is
/// available for this variable in the current scope.
llvm::SmallPtrSet<VarDecl*, 8> ReturnSlots;
...
};
Here, we need to explain a few terms:
Scopeitself is used when building the AST tree for a piece of code.VarDecl— a wrapper for a variable declaration or definition.ReturnSlots— a place in memory where we will allocate the function result.SmallPtrSetis a dynamic container with Small Buffer Optimization. The value 8 is the number of elements that can be stored on the stack. It doesn’t mean that we’re limited to that value. It’s just an optimization for some common case.
I personally don’t like the name «ReturnSlots» for that variable.
They’re not return slots actually.
They’re more like unchecked NRVO-candidates in the current scope.
NRVO also stores a candidate, but it’s the candidate which we’ve already selected from all the options.
You will see the difference in a moment.
When traversing the code and building the AST, we call the Scope::AddDecl function for each new variable declaration:
void AddDecl(Decl* D) {
if (auto* VD = dyn_cast<VarDecl>(D))
if (!isa<ParmVarDecl>(VD))
ReturnSlots.insert(VD);
...
}
When we encounter a declaration, we want to determine whether it’s a variable declaration (it could be a struct, for instance, or something else).
If it is, we check whether VD is a function parameter (ParmVarDecl).
If it is not, we can add the new variable to the list of possible NRVO-candidates.
It looks like this for our example:
S f(bool b) { // start Scope_1
S y; // Scope_1::AddDecl -> Scope_1::ReturnSlots = [S y]
if (b) { // start Scope_2
S s; // Scope_2::AddDecl -> Scope_2::ReturnSlots = [S s]
return s;
}
return y;
}
At that point, we need to understand how we should choose the best candidate.
The simplified call stack of related Clang functions looks like this:
Parse Code
|_ Parse Function Statement Body
|_ Parse Return Statement
|_ ActOnReturnStatement
|_ updateNRVOCandidate
Prepare. That code snippet will be the toughest in the whole article.
Let’s check updateNRVOCandidate implementation
(step by step):
void Scope::updateNRVOCandidate(VarDecl* VD) {
...
bool CanBePutInReturnSlot = false;
for (auto& S = this; S; S = S->getParent()) {
CanBePutInReturnSlot |= UpdateReturnSlotsInScopeForVD(S);
if (S->getEntity())
break;
}
...
}
What do we see here?
VDis aVarDeclof a variable which we found in areturnstatement.CanBePutInReturnSlotistrueif we could useVDas an NRVO-variable for any scope.- We update the NRVO candidates in all the outer scopes until we reach some «entity scope» (functions have «entity scopes», and
ifstatements, loops, and regular scopes do not).
What is that UpdateReturnSlotsInScopeForVD thing?
It’s declared at the beginning of updateNRVOCandidate:
void Scope::updateNRVOCandidate(VarDecl* VD) {
auto UpdateReturnSlotsInScopeForVD = [VD](Scope *S) -> bool {
bool IsReturnSlotFound = S->ReturnSlots.contains(VD);
S->ReturnSlots.clear();
if (IsReturnSlotFound)
S->ReturnSlots.insert(VD);
return IsReturnSlotFound;
};
bool CanBePutInReturnSlot = false;
for (auto& S = this; S; S = S->getParent()) {
CanBePutInReturnSlot |= UpdateReturnSlotsInScopeForVD(S);
if (S->getEntity())
break;
}
...
}
What we do is:
- Check whether the current scope’s NRVO-candidates contain the current
VarDecl. - Clear all the candidates.
- Return the current
VarDeclif it was there.
In fact, the whole UpdateReturnSlotsInScopeForVD function answers the question:
was VD declared in scope S?
That leaves us with one of two outcomes:
- leaving just one valid candidate (all the others are no longer valid)
- or removing all candidates because they were all invalid.
And at the end we make a decision about NRVO-value:
void Scope::updateNRVOCandidate(VarDecl* VD) {
auto UpdateReturnSlotsInScopeForVD = [VD](Scope *S) -> bool {
bool IsReturnSlotFound = S->ReturnSlots.contains(VD);
S->ReturnSlots.clear();
if (IsReturnSlotFound)
S->ReturnSlots.insert(VD);
return IsReturnSlotFound;
};
bool CanBePutInReturnSlot = false;
for (auto& S = this; S; S = S->getParent()) {
CanBePutInReturnSlot |= UpdateReturnSlotsInScopeForVD(S);
if (S->getEntity())
break;
}
NRVO = CanBePutInReturnSlot ? VD : nullptr;
}
So we either found a valid candidate or determined that NRVO isn’t possible in that context.
Not so clear, right?
Let’s check our example.
We reached return s parsing.
Here we need to call updateNRVOCandidate:
S f(bool b) { // start Scope_1
S y; // Scope_1::AddDecl -> Scope_1::ReturnSlots = [S y]
if (b) { // start Scope_2
S s; // Scope_2::AddDecl -> Scope_2::ReturnSlots = [S s]
return s; // <- updateNRVOCandidate(S s)
}
return y;
}
And now we need to update ReturnSlots for all scopes (the current one and its outer scopes).
That means that we apply UpdateReturnSlotsInScopeForVD to Scope_2 (which returns true, leaving Scope_2::ReturnSlots = [S s])
and then to Scope_1 (which returns false, leaving Scope_1::ReturnSlots = [], so S y is no longer a valid NRVO-candidate).
CanBePutInReturnSlot = true, which means that Scope_2::NRVO = VarDecl(S s).
So after parsing return s, we have the following state:
S f(bool b) {
S y; // Scope_1::AddDecl -> Scope_1::ReturnSlots = []
if (b) { // NRVO s
S s; // Scope_2::AddDecl -> Scope_2::ReturnSlots = [S s]
return s;
}
return y;
}
With that information, we need to apply NRVO to Scope_2.
The call stack here roughly looks like this:
ActOnFinishFunctionBody
|_ ActOnPopScope
|_ applyNRVO
Let’s check applyNRVO implementation:
void Scope::applyNRVO() {
if (!NRVO.has_value())
return;
if (*NRVO && isDeclScope(*NRVO))
(*NRVO)->setNRVOVariable(true);
...
getParent()->NRVO = *NRVO;
}
Of course, we can’t apply NRVO if we don’t have a Scope::NRVO candidate.
Then we check whether NRVO is allowed (*NRVO is nullptr if it isn’t, and non-null otherwise).
We also need to check whether the NRVO-candidate was declared in the current scope (isDeclScope).
If that’s not true, we don’t need to deal with that logic now.
Everything can be handled in the scope where the VarDecl stored in NRVO was declared.
And if all the conditions are true, we can set the NRVO-flag in the VarDecl pointed to by *NRVO.
At the end, we also propagate the valid NRVO-candidate to the parent scope. A bit more about that later.
Returning to our example:
S f(bool b) { // Scope_1::ReturnSlots = []
S y;
if (b) {
S s; // NRVO variable = true
return s; // NRVO happens!
}
return y;
}
Let’s end our example and parse the last return:
S f(bool b) { // Scope_1::ReturnSlots = []
S y;
if (b) {
S s;
return s; // NRVO happens!
}
return y; // <- updateNRVOCandidate(S y)
}
Since S y was already removed from Scope_1::ReturnSlots, Scope_1::NRVO is nullptr.
NRVO in Scope_1 is disallowed.
S f(bool b) { // NRVO = nullptr
S y;
if (b) {
S s;
return s; // NRVO happens!
}
return y; // NRVO can't happen :(
}
Okay. We have an NRVO-flag for some VarDecls.
How is that flag used?
First of all, that flag is the reason why we see the nrvo label in the AST.
Secondly, somewhere in the large Clang codebase, we have the CodeGenFunction class.
It’s responsible for generating a function’s intermediate representation.
And inside that class, we have a method that decides where we should allocate the variable represented by VarDecl D.
...
bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
...
if (NRVO) {
address = ReturnValue;
...
}
Here, bool NRVO consists of two things: whether our compiler settings allow NRVO in general and
whether D has the NRVO-flag.
If NRVO = true, we set the address variable.
And, importantly, address is the place in memory where the variable represented by VarDecl D will be allocated.
ReturnValue is the address of the function’s return slot.
So eventually, we tell the compiler that the variable D should be allocated in the function’s return slot.
That’s generally the whole optimization! Pretty straightforward, right?
Let’s draw some conclusions from what we saw.
First of all, NRVO doesn’t work smoothly today. Since the optimization happens during semantic analysis, the compiler doesn’t use all the available information. In fact, it uses a very specific subset of the available data. Let’s check that case:
template <bool B>
S f() {
S s; // def
if constexpr (B) {
if (false) {
return S();
}
}
return s; // mv
}
Obviously, that function is equivalent to:
S f() {
S s;
return s;
}
But because of the way Clang implements NRVO, we won’t get anything here.
That return S() clears the function’s ReturnSlots, and we don’t set NRVO with variable s.
There are other cases:
S f(bool b) {
S s;
if (b)
return s; // NRVO is not allowed...
else
return S(); // because of this
}
When we parsed the first return (return s), we actually set the function’s Scope::NRVO to VarDecl(S s).
But then we encountered return S() with VarDecl = nullptr (since we didn’t have a VarDecl for the returned value).
And that means that we call updateNRVOCandidate with a nullptr argument, which clears the function’s Scope::ReturnSlots.
And what’s more important, do you remember this propagation to the parent scope?
getParent()->NRVO = *NRVO;
Here, the function’s Scope::NRVO stored VarDecl(S s), but now it stores nullptr.
We concluded that we can’t use NRVO in that context.
Ideally, it should work because returning default-constructed s is the same as returning S().
But of course, we do have RVO for return S().
From that, we can deduce a simplified (but still correct) mental model:
NRVO works if we return the same local variable in all the return statements.
However, I’m not saying that NRVO is impossible in other cases. Let’s check our example with one change:
S f(bool b) {
if (b) {
S s;
return s;
}
S y;
return y;
}
We moved the declaration of y closer to its usage (more importantly, after return s).
Repeating all those simulations and manipulations of the NRVO logic, we will see that NRVO works for both variables in this case!
S f(bool b) { // Scope_1::ReturnSlots = []
if (b) { // Scope_2::ReturnSlots = []
S s; // Scope_2::ReturnSlots = [S s]
return s; // NRVO!
}
S y; // Scope_1::ReturnSlots = [S y]
return y; // NRVO!
}
Look. We just changed the place of the variable declaration, and it magically helped us make the code more performant! So we have one more reason to declare variables closer to their actual usage (apart from readability).
So, if you want to check whether NRVO is possible when using Clang, just reproduce your code structure and inspect the AST. Or walk through the process using all those rules.
GCC
While writing the blog post, I opened the GCC source code for the first time in my life. Welp…
I found it not so friendly. And I’m actually not sure that I understood everything about the implementation of NRVO. So we won’t explore the code itself. Instead, we will look at GCC’s behaviour through its great comments (they’re really useful and well-written, believe me) and some code examples.
The GCC logic today is like this:
- Check the first
returnin the function. Literally, the first one you encounter reading from top to bottom. Doesn’t matter if it is in some nested namespace. - If a variable is returned, check whether it could be an NRVO-candidate: it must be a local, non-static, non-volatile variable of the same type as the return type that hasn’t been optimized in another way.
- When we meet another
return, we check what it returns. The same variable as the firstreturn? Everything is okay. Another object or expression? Check whether the object returned by the firstreturnis still in scope. If it’s not, maybe we could still preserve NRVO. If it is, NRVO is impossible.
So, after simplification, the rule is:
- the first returned object is the candidate
- if it’s returned in all
returns, NRVO is in place - if it’s not, NRVO is only possible if the candidate is out of scope.
Let’s explore some examples.
First, the usual one:
S f() {
S s;
return s;
}
Everything is straightforward here.
Only one return of an object created in the current scope.
NRVO is here.
Let’s make it more complicated:
S f(bool x) {
S a;
if (x) {
return a;
}
return S{};
}
Here, our candidate is a.
When we see another return S{};, we check whether a is still in scope.
And it is!
So no NRVO here.
Here are the results:
S s = f(true);
def // S a
mv // move a in return
S s2 = f(false);
def // S a
def // S{} -> RVO works
Clang works in the same way here.
What if we move the initialization of a into the if?
S f(bool x) {
if (x) {
S a;
return a;
}
return S{};
}
After finding the candidate a in the second return, GCC checks whether a is still in scope.
And it is not!
So no need to break NRVO.
Both compilers give us:
S s = f(true);
def
S s2 = f(false);
def
Let’s check another case:
S f(bool b) {
if (b) {
S s;
return s;
}
S y;
return y;
}
In the case of GCC, we can be sure that NRVO is happening for return s.
But what about return y?
The thing is, by the time we reach return y, we already know that s is our candidate.
So any other variable can’t be NRVOed.
So here we have:
S s = f(true);
def // NRVO for return s
S s2 = f(false);
def // initialization of y
mv // move y in return
If you remember, Clang here was a bit more successful and made NRVO for both variables.
In another case, when you have an early return:
S f(bool b) {
if (b) {
return S{};
}
S y;
return y;
}
GCC should find an NRVO-candidate in the first return.
And since the first return doesn’t return an object, NRVO is ruled out
for all the other returns later:
S s = f(true);
def // RVO return S{}
S s2 = f(false);
def // initialize y
mv // return y
Clang also works better here.
If you try other, more complicated cases, you can also see that GCC is pickier.
We can describe the GCC pattern as «always return one variable in all the return statements».
MSVC
Since we can’t inspect MSVC’s code, we can learn by experimenting with examples. Let’s check known cases:
S f(bool x) {
S a;
if (x) {
return a;
}
return S{};
}
// S s = f(true);
// def
// mv
// S s = f(false);
// def
// def
No NRVO here. Only RVO in the second case (as expected).
Next case:
S f(bool x) {
if (x) {
S a;
return a;
}
return S{};
}
// S s = f(true);
// def
// mv
// S s = f(false);
// def
Unfortunately, unlike Clang and GCC, MSVC can’t perform NRVO in the first call.
In the case of an early return:
S f(bool b) {
if (b) {
return S{};
}
S y;
return y;
}
// S s = f(true);
// def
// S s = f(false);
// def
// mv
I suppose any return involving a temporary variable breaks NRVO completely in that compiler.
Here:
S f(bool b) {
if (b) {
S s;
return s;
}
S y;
return y;
}
// S s = f(true);
// def
// S s = f(false);
// def
MSVC behaves like Clang: NRVO for both returns, which is the ideal case.
But in a similar case with declaring y a bit earlier:
S f(bool b) {
S y;
if (b) {
S s;
return s;
}
return y;
}
// S s = f(true);
// def
// def
// mv
// S s = f(false);
// def
// mv
MSVC doesn’t do NRVO even for s, for some reason.
In their blog post, they write that (omitting details) NRVO is not possible if a function has multiple returned symbols with overlapping lifetimes. It seems that if you structure the code so that you create a variable only when you’re going to return it, everything should be fine. It’s very similar to what Clang does, but in practice (at least in simple cases), it doesn’t work with returns of prvalues.
Is it worth it?
The main question is: do you even need to think about NRVO? In most cases, you’ll get a move instead. And moving data is cheap, isn’t it?
Well, yes. Most of the time.
If you move a vector, it’s just 3 integers (okay, 2 integers and a pointer).
If you move a struct with a few small fields, it’s just a few small fields.
But what if you have a struct with 100 fields? You need to move all of them. What if you have inline storage?
struct Packet {
std::byte payload[4096];
};
What if your move constructor has some complicated side effect? As always, there are a lot of different cases.
My general belief is that the performance of our programs ultimately comes down to the system and the culture of writing fast code. You can’t write horrible programs all the time and start doing this differently only when you really need efficiency. It’s better to practice writing good code in every line and every function.
There is no need to optimize prematurely. But you don’t have to pessimize either.
Compilers and tooling
Clang and GCC enable NRVO by default.
To disable NRVO with those compilers, use -fno-elide-constructors.
Both compilers have -Wnrvo, which warns you if NRVO is possible but the compiler didn’t perform it.
I personally found that specific warning hard to use because the message it provides is not very clear.
But you can use it as an invitation to investigate whether NRVO is possible for a specific function and its variables.
For both compilers, -Wnrvo is not a part of -Wall.
You also can use -Wpessimizing-move, which tells you about cases when std::move breaks copy elision.
That flag is enabled automatically with -Wall.
In contrast with GCC, you also can use -Wreturn-std-move, which tells you when it’s actually better to use std::move in a return statement.
Clang also has that flag, but only for compatibility reasons. With no effect.
It’s also not a part of -Wall.
In MSVC, NRVO is available with optimizations enabled (/O2), since C++20 (/std:c++20) or with /permissive-.
Clang-tidy doesn’t have any specific checks for NRVO. But a few related options are available:
performance-no-automatic-movecould tell you whetherconstcan prevent an automatic move from areturn(because NRVO is optional it could lie)performance-use-std-movewhich will tell you when it’s better to usestd::move.
Other languages
In the Carbon programming language, you can declare a variable as returned, which means that
the variable will be returned by the function.
It allows the compiler to explicitly check for NRVO possibility and fail compilation in case of something preventing it.
It could actually be an interesting attribute to use in C++ compilers. At least for cases when you want to be sure that specific hot paths are very efficient.
Recommendations
So how should we write our code to be sure that we are doing our best from the perspective of NRVO?
- Return prvalues as much as possible.
- The type of the return value should be the same as the return type in the function signature.
- If you don’t want to think about all the scope analysis stuff, just try to return the same local variable in all the
returnstatements.
But, as always, don’t sacrifice code readability to get an optimization that doesn’t improve your code’s performance.
For Clang, you can use the godbolt.org AST viewer with equivalent code example (which only repeats the structure of your code, so you don’t need to paste NDA stuff there :D ).
Additional resources
Check out Arthur O’Dwyer’s talk if you want to explore returning in a wider sense: The Complete Guide to return x; - [CppNow 2021].