Search code examples
c++copy-constructorreturn-value-optimization

Impossible to disable return value optimization for std::string?


Given this minimal example.

#include <iostream>
#include <string>

void print_ptr(const std::string& s)
{
    const char* data = s.data();
    std::cout << "ptr: " << (void*)data << std::endl;
}

std::string str_return(const char* suffix)
{
    std::string s("prefix");
    s += " ";
    s += suffix;
    print_ptr(s);
    return s;
}

int main()
{
    std::string s = str_return("suffix"), t;
    print_ptr(s);
    t = str_return("suffix2");
    print_ptr(t);
    return 0;
}

I compiled like this:

g++ -std=c++98 -fno-elide-constructors -g -Wall  str_return.cpp -o str_return

My g++:

gcc version 4.7.1

The output:

ptr: 0x804b04c
ptr: 0x804b04c
ptr: 0x804b07c
ptr: 0x804b07c

Why are the pointers still equal?

  • It should not be return value optimization - I switched it off
  • It should not be move constructors since I took a really old standard of c++

How can I disable this behaviour?


Solution

  • Return value optimization affects the local object (s in your str_return function). You never instrument that.

    The string object itself manages dynamic memory and chooses to hand that managed memory over to the next string upon return. What you're instrumenting is that managed memory. Sensibly enough, that doesn't change.

    If you really want to see the effect of RVO, instrument the local object:

    #include <iostream>
    #include <string>
    
    void print_ptr(const std::string& s)
    {
        std::cout << "ptr: " << static_cast<const void *>(&s) << std::endl;
    }
    
    std::string str_return(const char* suffix)
    {
        std::string s("prefix");
        s += " ";
        s += suffix;
        print_ptr(s);
        return s;
    }
    
    int main()
    {
        std::string s = str_return("suffix");
        print_ptr(s);
        std::string t = str_return("suffix2");
        print_ptr(t);
    }