1

I want to make a factory style generator, which takes in A and outputs a subclass of A, RA (it adds information to A). I can't really think of a safe way to do this though.

structure:

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;

The safest way would probably be

  AR GenerateRA1(A&& a)
  {
    return AR(std::forward<A>(a),std::string("foo"));
  }

which would enforce that a is being destructed. Problem is that this causes the user to not ever to be able to use the argument of a in any way before the function call, which could be annoying:

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;
}

Is this OK? I can see calls to "a" going horribly awry without build in checks to see if the object has been destroyed.

4

1 回答 1

5
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移出(*),只有当用户明确请求移动(因此无需猜测)编译器才会移出目的。

于 2013-06-17T17:37:43.787 回答