考虑以下代码:
#include <vector>
#include <boost/noncopyable.hpp>
struct A : private boost::noncopyable
{
A(int num, const std::string& name)
: num(num),
name(name)
{
}
A(A&& other)
: num(other.num),
name(std::move(other.name))
{
}
int num;
std::string name;
};
std::vector<A> getVec()
{
std::vector<A> vec;
vec.emplace_back(A(3, "foo"));
// vec.emplace_back(3, "foo"); not available yet in VS10?
return vec; // error, copy ctor inaccessible
}
int main ( int argc, char* argv[] )
{
// should call std::vector::vector(std::vector&& other)
std::vector<A> vec = getVec();
return 0;
}
这不会在 VS2010 下编译,因为显然A
是noncopyable
并且因此std::vector<A>
无法复制。因此,我不能std::vector<A>
从函数中返回 a 。
但是,考虑到 RVO 的概念,我觉得这种事情是不可能的。如果此处应用了返回值优化,则可以省略复制构造并且调用getVec()
将有效。
那么这样做的正确方法是什么?这在 VS2010 / C++11 中是否可行?