I'm fairly new C++ and so I may not be using the correct terminology. Here is what I'm looking to do.
I have classes Foo and Bar. I'd like to create an instance of Foo. then I'd like to create an instance of Bar and pass the Foo instance to the constructor of Bar such that Bar now owns the lifetime of Foo. Such that when Bar's destructor is call, it will/should de-allocate the Foo instance.
Also, I'd like to make it obvious (using the correct C++ semantics) to the user's of Foo and Bar, that Bar owns the Foo instance.
I'm open to any advise/best practice suggestions as well.
Here is my attempt at this. What feels wrong to me is the delete &m_foo; in Bar's destructor. I also don't understand what :m_foo(foo) is really doing in Bar's ctor (and what is it called exactly - how would I speak it?). I would have thought making an assignment in the constructor would be correct.
class Foo
{
public:
Foo();
~Foo();
private:
};
Foo::Foo()
{
}
Foo::~Foo()
{
}
class Bar
{
public:
Bar(Foo & foo);
~Bar();
private:
Foo & m_foo;
};
Bar::Bar(Foo & foo)
:m_foo(foo)
{
}
Bar::~Bar()
{
delete &m_foo;
}
Here is How I'd like to use it
int main()
{
auto foo = new Foo();
auto bar = new Bar(*foo);
delete bar;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire