C++共享指针.如何更改所有副本的基础对象的指针?

Que*_*onC 5 c++ boost

虚拟课我有一个奇怪的情况,我需要设计帮助.

  1. 对象确实可以破坏,
  2. 对象存储在向量中,但是我需要从向量中获取对象或对它的引用,更改它,并将该更改反映在对象的所有"副本"中,
  3. 我希望这些对象可以复制.

我有一个解决方案,但我正在寻找一个更好的解决方案.这是我编写的代码,它完成了我正在寻找的东西,但它依赖于指向指针的指针.

我觉得如果我可以直接操作共享指针的底层数据指针,我可以减少一层抽象.

我想用一个InterfaceWrapper,而不是两个.

#include <stdio.h>
#include <memory>
#include <vector>

class Interface
{
  public:
    virtual void WriteIt() = 0;
    virtual ~Interface() { }
};

class Foo : public Interface
{
  void WriteIt() { printf ("Foo\n"); }
};

class Bar : public Interface
{
  void WriteIt() { printf ("Bar\n"); }
};

// This class wraps Interface so we can call WriteIt on desctruction
// I'd like to do this in the Interface class, but you can't call virtual methods during destruction.
class InterfaceWrapper : public std::unique_ptr<Interface>
{
  public:
  InterfaceWrapper(Interface * i) : std::unique_ptr<Interface>(i) { }
  ~InterfaceWrapper() { (*this)->WriteIt(); }
};

// This class provides counted destruction to InterfaceWrapper
class InterfaceWrapper2
{
  public:
    InterfaceWrapper2 () : _ptr(new InterfaceWrapper(new Foo)) { }

    void MakeBar() { _ptr->reset(new Bar); }

  private:
    std::shared_ptr<InterfaceWrapper> _ptr;
};

int main (void)
{
  std::vector<InterfaceWrapper2> thing_vector;

  // The default implementation will, print "Foo" on destruction.
  InterfaceWrapper2 thing;

  // That destructor should only happen once for all copies of 'thing'
  thing_vector.push_back(thing);

  // MakeBar changes the virtual implementation so it prints "Bar" instead of "Foo"
  thing.MakeBar();

  // When destructors happen, the program should just print "Bar" once.

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

欢迎任何事情,但我特别感兴趣的是使用boost在C++ 03上工作的解决方案(我的例子是C++ 11,但我的'真正的'代码是使用boost :: shared_ptr的C++ 03).

澄清

我基本上是在寻找在我的示例代码中实现InterfaceWrapper2的更好方法. main()是我想要完成的最好的解释.只记得行为被困在那些虚拟类中.

jxh*_*jxh 0

借鉴sehe 的精彩见解,这个版本为您提供了更接近于 C++.2003 中可以做的事情:

class InterfaceWrapper {
    typedef std::unique_ptr<Interface> UI;
    std::shared_ptr<UI> p_;
public:
    InterfaceWrapper () : p_(std::make_shared<UI>(new Foo)) {}
    ~InterfaceWrapper () { if (p_.unique()) (*p_)->WriteIt(); }
    void MakeBar() { p_->reset(new Bar); }
    const UI & operator -> () { return *p_.get(); }
};
Run Code Online (Sandbox Code Playgroud)

我选择在 的析构函数中添加条件,而不是自定义删除器InterfaceWrapper。这允许构造函数使用std::make_shared.