【发布时间】:2016-06-17 15:37:53
【问题描述】:
#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()) 无法编译,因为 bar 接受非常量引用,foo 返回右值。但是带有std::auto_ptr 的第二行编译。 std::auto_ptr 的复制构造函数也接受非常量引用。为什么它会编译?我在foo1 中使用了std::rand() 来消除RVO(返回值优化)。
【问题讨论】:
-
[FYI]
std::auto_ptr已弃用。它已被std::unique_ptr和std::shared_ptr取代。 -
我知道但仍然需要使用旧的编译器。
-
您可能想要指定 c++98 或 C++03。 C++ 本身包括当前的标准,即 C++14。
标签: c++ copy-constructor c++03 c++98 auto-ptr