gpt4 book ai didi

c++ - 私有(private)类实现中的Pimpl和指针

转载 作者:行者123 更新时间:2023-11-28 04:17:30 24 4
gpt4 key购买 nike

我有以下 Pimpl 类,其中 FooPrivate 类中的成员之一是指向应在 Foo:init() 中动态分配的类 A 的指针并在 Foo:stop()Foo 的 dtor 中销毁。到目前为止我有这个:

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

我关心的是 A *a 的所有权以及分配应该在代码中的什么地方进行?在 Foo 类或 FooPrivate 中?

创建像 FooPrivate::init()FooPrivate::stop() 这样的辅助函数是否更干净,它们将从 Foo:init 调用()Foo:stop(),同时删除 FooPrivate 的 dtor 中的 A *a 而不是?

谢谢。

最佳答案

My concern is about the ownership of A *a

然后使用智能指针,比如:

std::unique_ptr<A> a;

关于c++ - 私有(private)类实现中的Pimpl和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56290401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com