class A (abstract)
class B : A
class C
{
void add ( A(&*?) a )
std::vector<std::unique_ptr<A>> data; //unique_ptr<A> because A is abstract and therefore vector<A> isn't possible
}
upper situation. What is the best way to pass add an object of class B to C?
with C::add(A* a){ vector.push_back( unique_ptr<A>(a) ); }
and
1 2 3 4 5
int main()
{
C c;
c.add( new B() );
}
This works, but i don't think it's very nice, because you could delete the pointer in main. What happens then with the unique_ptr?
I could probably make C::add( std::unique_ptr<A> u_p ); but maybe it can be avoided that the "user" (in main() ) has to create the unique_ptr himself.
Do you have a recommendation, what is a nice way to solve this?
#include <vector>
#include <memory>
class A
{
virtualvoid a()=0;
};
class B : public A
{
virtualvoid a(){};
};
class C
{
public:
void add ( A* a ) { data.emplace_back( a ); };
private:
std::vector<std::unique_ptr<A>> data;
};
int main()
{
B* a=new B();
C c;
c.add( a );
delete a;
}
this code compiles fine and gives an error when running the programm.
But according to your link, best would be to use unique_ptr<A> as argument, I think.