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?
str_return(). This strongly hints at a bug/non-standard behaviour of the library. When using the llvm libc++, the pointers are different (though it reusess.data()int, i.e. the 1st and 3rd line report the same ptr).std::stringwhich is 100% conforming in C++03 (which this example uses)std::string copy(s.data(), s.size()), but in this example that's just a harmful pessimisation, because afterstr_returnreturnssandtare not sharing their data with another object anyway.