通过类本身检测“ this”的更改

时间:2018-06-21 07:30:09

标签: c++

如果我有一些定义了复制/移动构造函数和运算符的类,是否可以确定我的类知道其“ this”指针的任何更改?需要能够将“ this”指针的更改通知其他类。然后其他类将能够更新其指针并访问该类中的数据。

示例:

#include <iostream>

// complex class with support of move semantics
struct Data { int x = 0; };

class A;

// this class often access A::data
// but if A is destroyed it stops doing this
struct B {
        void notify(A* newPointer);
        void access();
        A* pointer = 0;
};

struct A {
        A(B* b) {
                this->b = b;
                if(b) b->notify(this);
        }
        A(A&& a) {
                /* current data will be substituted by new data, 
                 * so object b which depends on it should be 
                 * notified to stop listening */
                if (b) b->notify(0); 

                data = std::move(a.data); // now transfer the data

                b = a.b;

                /* b will know that data is transfered to new class */
                if (b) b->notify(this);

                /* old class will stop notifying b, 
                 * because it doesn't hold the data */
                a.b = 0;
        }
        void operator=(A&& a) {
                if (b) b->notify(0);
                data = std::move(a.data);
                b = a.b;
                if (b) b->notify(this);
                a.b = 0;
        }
        ~A() {
                if (b) b->notify(0);
        }
        B* b = 0;
        Data data;
};

void B::notify (A* newPointer) { pointer = newPointer; }

void B::access () {
        if (pointer) {
                pointer->data.x += 1;
        }
}

int main() {
        B b;
        {
                A a(&b);
                b.access(); // x = 1
                A a2 = std::move(a);
                b.access(); // x = 2
                a = std::move(a2);
                b.access(); // x = 3
                std::cout << a.data.x << std::endl;
        }
        b.access(); // b doing nothing
}

此实现是否100%健壮?构造函数和运算符=是否了解有关“ this”更改的所有信息?


如果您觉得我选择了错误的措辞来解释问题,我将感谢有关改进的建议。

0 个答案:

没有答案