在我的工作场所,我们有这样的约定:几乎每个类(除了极少数例外)都使用unique_ptrs、原始指针或引用作为成员变量来实现。
这是因为编译时间的原因:通过这种方式,您只需要在头文件中对类进行前向声明,并且只需要在 cpp 中包含该文件。此外,如果您更改包含的类的 .h 或 .cpp,unique_ptr则不需要重新编译。
我认为这种模式至少有以下缺点:
std::vector<std::unique_ptr<MyClass>>而不是更简单的std::vector<MyPimplClass>.因此,我想到建议对作为指针包含的类使用 pImpl 习惯用法,而不是在任何地方使用指针。通过这种方式,我认为我们可以两全其美:
A::A(const A& rhs) : pImpl(std::make_unique<Impl>(*rhs.pImpl)) {}
A& A::operator=(const A& rhs) {
*pImpl = *rhs.pImpl;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
在这一点上,我与我的同事进行了讨论,他们认为 pImpl 并不比在任何地方使用指针更好,原因如下:
现在我有点困惑。我认为我们的实际约定并不比 pImpl 好,但我无法争论为什么。
所以我有一些问题:
编辑:我正在添加一些示例来阐明这两种方法。
unique_ptr为成员:// B.h
#pragma once
class B {
int i = 42;
public:
void print();
}; …Run Code Online (Sandbox Code Playgroud) 我想在 C++ 中尝试使用 PIMPL。
就我而言,我正在使用operator()访问私人成员。
接口类A和实现类AImpl都有operator() const和operator()。
代码如下所示:
#include <iostream>
class AImpl
{
public:
explicit AImpl()
{
x = 0;
}
const int &operator()() const
{
std::cout << "const access in AImpl" << std::endl;
return x;
}
int &operator()()
{
std::cout << "not const access in AImpl" << std::endl;
return x;
}
private:
int x;
};
class A
{
public:
A()
{
impl = new AImpl;
}
~A()
{
delete …Run Code Online (Sandbox Code Playgroud)