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.