Search code examples
c++nrvo

Why should one rely on Named Return Value Optimization?


I was reading about NRVO and trying to understand when should one rely on it and when not. Now I have a question: why should one rely on NRVO at all? It is always possible to explicitly pass a return parameter by reference, so is there any reason to rely on NRVO instead?


Solution

  • Dealing with return values is simply easier than dealing with methods that return by writing to a reference parameter. Consider the following 2 methods

    C GetByRet() { ... }
    void GetByParam(C& returnValue) { ... }
    

    First problem is that it makes it impossible to chain method calls

    Method(GetByRet());  
    // vs. 
    C temp;
    GetByParam(temp);
    Method(temp);
    

    It also makes features like auto impossible to use. Not so much of a problem for a type like C but more important for types like std::map<std::string, std::list<std::string>*>

    auto ret = GetByRet();
    // vs.
    auto value; // Error! 
    GetByParam(value);
    

    Also as GMacNickG pointed out, what if the type C has a private constructor that normal code can't use? Maybe the constructor is private or there just isn't a default constructor. Once again GetByRet works like a champ and GetByParam fails

    C ret = GetByRet();  // Score! 
    // vs.
    C temp; // Error! Can't access the constructor 
    GetByParam(temp);