【发布时间】:2013-11-08 20:21:06
【问题描述】:
以下代码无法在 Visual C++ 2008 和 2010 上编译:
#include <memory>
struct A {};
std::auto_ptr<A> foo() { return std::auto_ptr<A>(new A); }
const std::auto_ptr<A> bar() { return std::auto_ptr<A>(new A); }
int main()
{
const std::auto_ptr<A> & a = foo(); // most important const
const std::auto_ptr<A> & b = bar(); // error C2558:
// class 'std::auto_ptr<_Ty>' :
// no copy constructor available or copy
// constructor is declared 'explicit'
bar(); // No error?
}
我希望将“最重要的 const”应用于变量“b”,但它没有编译,并且由于某种原因,编译器要求使用复制构造函数(这让我感到惊讶,因为不应该有复制此处涉及)。对bar() 的独立调用工作正常,这意味着,我猜,这确实是b 的初始化问题。
这是编译器错误,还是标准中描述的真正编译错误?
(也许在 C++98 中被禁止,在 C++11 中被授权?)
注意:它可以在 Visual C++ 2012、gcc 4.6 和 Solaris CC(所有编译器...)上编译,但不能在 gcc 3.4 和 XL C 上编译)
【问题讨论】:
-
你是否包含了
? -
是的,我做到了... :-) ...我会更新帖子以显示这一点。
-
@SHR 如果您打算将所有权转移给调用者,则返回
auto_ptr非常好。 -
返回
auto_ptr很好,因为有很多auto_ptr_ref诡计专门设计用于使这种事情发挥作用。 -
@ZacHowland:可能是因为如果您使用的是 VS2008、VS2010、gcc 3.4 和 xlC,
std中没有unique_ptr。auto_ptr至少在所有这些编译器支持的 C++ 版本中是标准化的。