Skip to content

NRVO not eliding copy for std::string with early exit #158594

@firewave

Description

@firewave
#include <string>

std::string f(int maxsize)
{
    std::string ret;
    for (int i = 0; ; ++i)
    {
        if (i > maxsize)
            return "";
        ret += ".";
    }
    return ret;
}
<source>: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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions