#include <iostream>
#include <string>
#include <memory>
#include <cstdlib>
std::string foo()
{
return std::string("yyyyyyyyyyyyy");
}
void bar(std::string& s)
{
std::cout << s << std::endl;
}
std::auto_ptr<std::string> foo1()
{
bool x = std::rand() % 2;
if (x) {
return std::auto_ptr<std::string>(new std::string("eeeeeeeeeeee"));
} else {
return std::auto_ptr<std::string>(new std::string("aaaaaaaaaaaaa"));
}
}
int main()
{
//bar(foo());
std::auto_ptr<std::string> a(foo1());
}
The commented line: bar(foo())
doesn't compile because bar accepts non-const reference and foo
returns rvalue. But the second line with std::auto_ptr
compiles. Copy constructor of std::auto_ptr
also accepts non-const reference. Why then it compiles? I used std::rand()
in foo1
to eliminate RVO (Return value optimization).