1

假设我们有三个类:A、B、C。A 和 B 都拥有一个指向 C 类的指针。永远不会发生类 A 的两个实例共享同一个指向对象 C 的指针,但是,同时,对象 C 可以自由地被 B 类的实例指向。

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

======编辑======

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

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

4

2 回答 2

1

如果将同一个指针分配给多个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;
}
于 2013-03-18T15:48:50.887 回答
0

我认为您需要在班级内部做一些簿记,也许使用静态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;
}
于 2013-03-18T15:48:41.073 回答