class Member {
public:
    Member(int idx) {
        this->idx_ = idx;
    }

    int get_idx() {
        return idx_;
    }

    void set_idx(int idx) {
        this->idx_ = idx;
    }

    void foo();

private:
    int idx_;
};


class SingletonClass {
public:
    static SingletonClass& GetInstance() {
        static SingletonClass inst;
        return inst;
    }

    vector<Member*> get_members() {
        return this->members_;
    }

    Member* get_member(int idx) {
        return this->members_[idx];
    }

    void add_member(Member* mem) {
        this->members_.push_back(mem);
    }

private:
    SingletonClass() {}
    vector<Member*> members_;
};

void Member::foo() {
    SingletonClass inst = SingletonClass::GetInstance();
    cout << inst.get_members().size();
}


int main() {
    SingletonClass inst = SingletonClass::GetInstance();
    inst.add_member(new Member(0));
    inst.add_member(new Member(1));
    cout << inst.get_members().size() << endl;

    Member* mem = inst.get_member(1);
    mem->foo();
    return 0;
}

输出是
2
0

看来,当我在Member::foo()中获得SingletonClass的实例时,members_的成员变量 vector SingletonClass被清除了……有人可以向我解释为什么以及如何发生吗?我该如何解决它以获得预期的结果?非常感谢!

最佳答案



您正在以下行中复制对象:

SingletonClass inst = SingletonClass::GetInstance();

然后您正在修改副本的内容。原始对象保持不变。

使用:
SingletonClass& inst = SingletonClass::GetInstance();

为防止这种情况在代码的其他地方发生,请明确删除复制构造函数和复制赋值运算符。
private:
    SingletonClass() {}
    SingletonClass(SingletonClass const&) = delete;
    SingletonClass& operator=(SingletonClass const&) = delete;
    vector<Member*> members_;

09-25 16:59