llvm / llvm/llvm-project

NRVO not eliding copy for `std::string` with early exit

Open
#158,594 7 comments 0 reactions 0 assignees View on GitHub
c++ clang:frontend missed-optimization
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

```cpp
#include

std::string f(int maxsize)
{
std::string ret;
for (int i = 0; ; ++i)
{
if (i > maxsize)
return "";
ret += ".";
}
return ret;
}
```

```
:12:12: warning: not eliding copy on return [-Wnrvo]
12 | return ret;
| ^
```
https://godbolt.org/z/fPfEGMh7E

Clearing `ret` and returning it addresses the warning but feels a bit awkward.

This also occurs without the loop but such a case can easily be mitigated without uglifying the code.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the warning with the C++ example and Godbolt link, then trace the compiler's NRVO analysis and diagnostic for the early-exit case. The issue is addressed when the behavior is intentionally corrected or documented with a regression test covering this example.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.