类中唯一的指针

unique pointer within a class

本文关键字:指针 唯一      更新时间:2023-10-16

假设我们有三个类:A, B, C。A和B都拥有一个指向类C的指针。永远不应该出现类A的两个实例共享指向对象C的同一个指针,但同时对象C可以被类B的实例自由指向的情况。

有没有办法在c++(11)中实现这个?

编辑

= = = = = = = = = = = =

好的,让我们更详细地讲一下。当我创建对象C时,我将它们的指针添加到对象b中的容器中。对象a可能拥有或不拥有指向C的指针。重要的是,不超过一个a指向同一个C,这实际上可能是由于用户的错误而发生的。一旦A先验地指向C,它就应该一生都指向C。

我本来会选择唯一指针,但我需要它们的副本到B的容器中!

听起来,如果同一个指针被分配给多个A实例,则需要抛出异常。

该解决方案可以跟踪已使用的指针以防止重赋值。不是线程安全的…如果需要的话,您必须修改它以添加同步。

class A
{
  // The pointers used by all instances of A
  static std::set<C*> used_ptrs;
  // The pointer used by this instance of A
  C* the_c;
  // Sets the pointer if it is valid
  void set_c( C* c )
  {
    if ( the_c )
      throw std::runtime_error( "C pointer is already set in this A" );
    if ( used_ptrs.count( c ) )
      throw std::runtime_error( "C pointer is already set in another A" );
    the_c = c;
    used_ptrs.insert( c );
  }
  // The pointer is presumed to be unassigned at construction
  A() : the_c(NULL) {}
  // The pointer is removed from the set at destruction
  ~A()
  {
    if( the_c );
      used_ptrs.erase( the_c );
  }
  // Copying A is invalid by your description
  A( const A& ) = delete;
  A& operator= ( const A& ) = delete;
}

我认为您需要在类内部做一些簿记,也许使用静态unordered_map成员。我已经测试了下面的代码工作:

using namespace std;
struct C;
struct A
{
  void SetPointerToC(C & aC)
  {
    if ( mAllC.find(&aC) != mAllC.end() )
      assert(false); // multiple instances of A should not point to the same C
    mAllC[&aC] = this;
    mC = &aC;
  }
  ~A()
  {
    mAllC.erase(mC);
  }
private:
  // A is not copyable as to prevent multiple A instances having 
  // mC with the same value
  A(const A &);
  A & operator=(const A &);
  static unordered_map<C*, A*> mAllC;
  C * mC;
};
unordered_map<C*, A*> A::mAllC;
struct C
{
};
int _tmain(int argc, _TCHAR* argv[])
{
  A a;    
  A a2;
  C c;
  a.SetPointerToC(c); // works
  a2.SetPointerToC(c); // assert!
  return 0;
}