Reputation: 2211
I have the following Pimpl class where one of the member in the FooPrivate
class is a pointer to a class A that should be dynamically allocated in Foo:init()
and destroy in Foo:stop()
or in the dtor of Foo
. So far i have this :
foo.h :
#ifndef FOO_H
#define FOO_H
#include <QtGlobal>
class FooPrivate;
class Foo
{
public:
Foo();
void init(); // here we should dynamically instanciate an object of class A
~Foo();
private:
Q_DISABLE_COPY(Foo)
Q_DECLARE_PRIVATE(Foo)
FooPrivate * const d_ptr;
};
#endif // FOO_H
foo.cpp :
#include "foo.h"
#include "foo_p.h"
#include "a.h"
Foo::Foo()
: d_ptr(new FooPrivate)
{
Q_D(Foo);
d->a = nullptr;
}
void Foo::init()
{
Q_D(Foo);
if (d->a) // init should happen only once
return;
// and d->a should be instanciated here
d->a = new A;
}
void Foo::stop()
{
Q_D(Foo);
delete d->a;
d->a = nullptr;
}
Foo::~Foo()
{
Q_D(Foo);
delete d->a;
delete d_ptr;
}
foo_p.h :
#ifndef FOOPRIVATE_H
#define FOOPRIVATE_H
class Foo;
class A;
struct FooPrivate
{
FooPrivate() {}
A *a;
};
#endif // FOOPRIVATE_H
My concern is about the ownership of A *a
and where the allocation should take place in the code ? in Foo
class or in FooPrivate
?
Is it more clean to create helper functions like FooPrivate::init()
and FooPrivate::stop()
that will be call from Foo:init()
and Foo:stop()
, and also delete A *a
in the dtor of FooPrivate
instead ?
Thank you.
Upvotes: 0
Views: 121
Reputation: 27567
My concern is about the ownership of A *a
Then use a smart pointer, something like:
std::unique_ptr<A> a;
Upvotes: 1