C ++-指向不同对象具有相同地址但值不同的另一个非静态成员的非静态void *成员

This question title is not clear and a bit broken. I tried to use a void* whihch is a member to store the address of another member. I accidentally found a weird problem. There were three Object objects created inside a vector<T>. But when I look at the value of those three val_addr, they always point to the same address, but appreantly each val is always unique.

class Object {

protected:
    int val {0};

    void *val_addr = nullptr;

    std::vector<Object> objs;

public:
    Object() = default;

    Object(int val) 
    {
        this->val = val;
        this->val_addr = (void *) &this->val;
        std::cout << "val_addr: " << val_addr << "\n"; // always 0X123456 for example
    }

    std::vector<Object> &get_objs() const 
    {
        return objs;
    }

};

class Iterable : public Object {
public:
    Iterable(const std::set<int>& values) { // {1, 2, 3} inside values
        for (const auto & c : values) {
            this->values.emplace_back(c);
        }
    };
};
评论