用于保持对象引用的智能指针

时间:2016-09-21 06:36:03

标签: c++ pointers forward-declaration

假设我有这个标题:

#include <vector>

class B;

class A
{
...
private:
    std::vector<what_pointer B> holder;
};

我不想在标题中包含B,所以我制作了&#34; B&#34;向前引用它。但是标题有B的那个容器,并且因为B的真正标题只包含在Cpp中,所以我必须在容器内使用指向B的指针。

显然,我可以为A创建一个析构函数,它通过&#34; holder&#34;并且de分配指针指向的所有内存区域。但是我想知道是否有一个智能指针&#34;应该&#34;在这种情况下使用而不是原始指针。

1 个答案:

答案 0 :(得分:1)

  • 在c ++ 17中,您可以直接执行

    class B;
    
    class A
    {
    public:
    ...
        ~A(); // define in cpp, as B definition should be known for destruction
    private:
        std::vector<B> holder;
    };
    

    vector

  • 而允许不完整的类型
  • 目前,您可以

    class A
    {
    public:
        //...
        A(const A&); // should be reimplemented to copy holder
        A& operator =(const A&); // should be reimplemented to copy pimpl
        A(A&&) = default;
        A& operator =(A&&) = default;
    
        ~A();
    private:
        std::vector<std::unique_ptr<B>> holder;
    };
    

    然后

    #include "B.h"
    
    // define in cpp, as B definition should be known
    ~A::A() = default;
    
    A::A(const A& rhs) {
        for (const auto& b : rhs.holder) {
             holder.push_back(std::make_unique<B>(*b));
        }
    }
    
    // ...
    
  • 或完全使用pimpl成语

    class A
    {
    public:
        //...
        A(const A&); // should be reimplemented to copy pimpl
        A& operator =(const A&); // should be reimplemented to copy pimpl
        A(A&&) = default;
        A& operator =(A&&) = default;
    
        ~A();
    private:
        struct Pimpl;
        std::unique_ptr<Pimpl> pimpl;
    };
    

    然后

    #include "B.h"
    
    struct A::Pimpl {
        // ...
        std::vector<B> holder;
    };
    
    // define in cpp, as B definition should be known
    ~A::A() = default;
    
    A::A(const A& rhs) : pimpl(std::make_unique<Pimpl>(rhs.pimpl)) {}
    
    // ...
    
相关问题