C++ 11 的"Move Factory"
"Move Factory" for c++ 11
我想做一个工厂风格的生成器,它接受A并输出A,RA的子类(它向A添加信息(。不过,我真的想不出一种安全的方法。
结构:
class A
{
public:
std::string str;
A(std::string a)
{
str = a;
}
A(A&& a) :
str(std::move(a.str))
{
}
};
class AR : public A
{
public:
std::string str1;
AR(std::string a,std::string b) : A(a)
{
str1 = b;
}
AR(A &&a,const std::string& b)
: A(std::forward<A>(a))
{
str1 = b;
}
AR(AR&& ar)
: A(std::forward<A>(ar)),
str1(std::move(ar.str1))
{
}
};
class ARFactory;
最安全的方法可能是
AR GenerateRA1(A&& a)
{
return AR(std::forward<A>(a),std::string("foo"));
}
这将强制 A 正在被破坏。问题是这会导致用户在函数调用之前以任何方式使用 a 的参数,这可能会很烦人:
ARFactory fact;
{
AR ar=fact.GenerateRA1(A("bar"));//compiles
}
{
A a("bar");
a.str += "1";
//AR ar = fact.GenerateRA1(a);//doesn't compile
AR ar = fact.GenerateRA1(std::move(a));//does...reference to a is still around, but destroyed
std::cout << "a.str=" << a.str << " b.str=" << ar.str << " ar.str1=" << ar.str1 << std::endl;
}
可以吗?我可以看到对"a"的调用在没有内置检查以查看对象是否已被破坏的情况下变得非常错误。
AR ar = fact.GenerateRA1(std::move(a));//does...reference to a is still around, but destroyed
用户请求您将内容从a
移动到函数中,她知道a
的内容可能已被移动,并且知道类型A
她知道对象可以做什么或不可以做什么a
。这不是问题,这就是事情的运作方式。
//AR ar = fact.GenerateRA1(a); //doesn't compile
这正是重点。编译器拒绝此代码,因此用户不需要检查a
是否移出 (*(,只有当用户显式请求移动(因此无需猜测即可知道(编译器将移出对象时。
相关文章:
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- Usages of std::move
- 在C++中对T*类型执行std::move的意外行为
- 关于std::move的使用,是否有编译警告
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 通过实例理解std::move及其目的
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- 返回一个带有 std::move 的对象并链接函数
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 当 std::move 与 C 样式数组或不移动对象时会发生什么
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 添加自定义析构函数时,Move 构造函数在派生类中消失
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- CPP 中的瓦尔格林德和记忆泄漏:"Conditional jump or move depends on uninitialised values"
- std::move a const std::vector in a lambda capture
- "std::forward"和"std::move"真的不生成代码吗?
- std::vector move 而不是交换到空 vector 并释放存储
- C++ 11 的"Move Factory"