我认为您需要在班级内部做一些簿记,也许使用静态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;
}