给定一个不可复制但可移动的类型,我正在尝试构造boost::ptr_vector
这种类型的 a 并从函数中返回它。我正在使用 Visual Studio 2013。
struct NonCopyableButMovable
{
using this_type = NonCopyableButMovable;
this_type() {}
this_type(this_type const &) = delete;
this_type & operator =(this_type const &) = delete;
this_type(this_type &&) {} // no default move ctr in VS2013
this_type & operator =(this_type &&) {} // no default move assignment in VS2013
};
boost::ptr_vector<NonCopyableButMovable> make_ptr_vector()
{
boost::ptr_vector<NonCopyableButMovable> res;
//return res; // (1)
//return std::move(res); // (2)
return boost::ptr_vector<NonCopyableButMovable>(); // (3)
}
我只能得到 (3) 来编译:临时ptr_vector
的被移动了。使用 (1) 和 (2),编译器调用boost::new_clone
试图调用NonCopyableButMovable
的复制构造函数。
根据这个常见问题解答,“移出功能”部分,(1)应该可以工作,即res
应该移动,而不是复制。
根据这个线程,(2)可以用作不完全符合标准的编译器的解决方法,但由于我不明白的原因,boost::new_clone
也可以用(2)调用。
请注意,如果我替换boost::ptr_vector
为std::vector
,则三种返回编译方式都很好。
VS2013 的 Boost ptr_containers 移动语义是否有问题?情况(2)会发生什么?实现这样的 ptr_container 工厂函数的解决方法是什么?