【发布时间】:2011-02-10 12:53:19
【问题描述】:
我最近安装了 Visual Studio 2010 Professional RC 来试用并测试在 VC++ 2010 中实现的少数 C++0x 功能。
我实例化了std::vector 的std::unique_ptr,没有任何问题。但是,当我尝试通过将临时变量传递给push_back 来填充它时,编译器会抱怨unique_ptr 的复制构造函数是私有的。我尝试通过移动它来插入一个左值,它工作得很好。
#include <utility>
#include <vector>
int main()
{
typedef std::unique_ptr<int> int_ptr;
int_ptr pi(new int(1));
std::vector<int_ptr> vec;
vec.push_back(std::move(pi)); // OK
vec.push_back(int_ptr(new int(2))); // compiler error
}
事实证明,问题既不是unique_ptr也不是vector::push_back,而是VC++在处理右值时解决重载的方式,如下代码所示:
struct MoveOnly
{
MoveOnly() {}
MoveOnly(MoveOnly && other) {}
private:
MoveOnly(const MoveOnly & other);
};
void acceptRValue(MoveOnly && mo) {}
int main()
{
acceptRValue(MoveOnly()); // Compiler error
}
编译器抱怨无法访问复制构造函数。如果我将其公开,则程序会编译(即使未定义复制构造函数)。
我是否误解了有关右值引用的某些内容,或者它是 VC++ 2010 实现此功能的一个(可能已知的)错误?
【问题讨论】:
标签: c++ visual-studio-2010 visual-c++ c++11 rvalue-reference