#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());
}
コメント行:bar(foo())
バーは非const参照を受け入れ、foo
はrvalueを返すため、コンパイルされません。しかし、std::auto_ptr
の2行目がコンパイルされます。 std::auto_ptr
のコピーコンストラクタも非const参照を受け入れます。なぜそれがコンパイルされますか?私はfoo1
にstd::rand()
を使ってRVO(戻り値の最適化)を排除しました。std :: auto_ptrはrvalueでどのように初期化されますか?
[FYI] 'のstd :: auto_ptr'は推奨されています。これは 'std :: unique_ptr'と' std :: shared_ptr'に置き換えられました。 – NathanOliver
私は知っていますが、古いコンパイラを使用する必要があります。 – Ashot
C++ 98またはC++ 03を指定することができます。 C++自体には現在の標準であるC++ 14が含まれています。 – NathanOliver