Accessing member variables through static pointer to instance

I have a class with a static vector of pointers to all instances of the class. When I access the member variables through a static getter method, I sometimes get wrong results.

Code:
hpp-file:

class ObjectID {
    public:
        ObjectID();
        float getShininess() const { return m_shininess; }
        static const std::shared_ptr<ObjectID> getID(unsigned long);
    private:
        float m_shininess;
        static std::vector<std::shared_ptr<ObjectID>> s_ids;
}

cpp-file:

static std::mutex s_mutex;
std::vector<std::shared_ptr<ObjectID>> ObjectID::s_ids = {};

const std::shared_ptr<ObjectID> ObjectID::getID(unsigned long id) {
    std::lock_guard<std::mutex> lock(s_mutex);
    std::shared_ptr<ObjectID> ptr = s_ids.at(id - 1);
    return ptr;
}

ObjectID::ObjectID()
  : m_shininess(50.f)
{
    std::lock_guard<std::mutex> lock(s_mutex);
    s_ids.emplace_back(this);
}

I have a suspicion that it has something to do with the fact that I use two threads. However adding the mutex did not change anything.

For clarification, one thread creates ObjectIDs and another thread calls

ObjectID::getID(id)->getShininess();

I don't always get 50, sometimes I get 1, and I am never changing m_shininess. Any ideas?

EDIT :

ObjectIDs are created in another class, which has a vector of ObjectIDs.

m_objects.emplace_back();

Your vector holds shared_ptr, but you are emplacing raw pointers to ObjectID (this) into it. Since shared_ptrs can be constructed from raw ones this compiles, but it probably isn't doing what you want it to. In particular, you will wind up with wild pointers in that vector if an ObjectID gets destroyed though other means. I don't know for sure that this is the cause of your problem, but it is at least suspicious.

I don't know your exact requirements, but maybe something like this would help?

class ObjectID
{
public:
   static std::shared_ptr<ObjectID> Create()
   {
       auto created = std::make_shared<ObjectID>();
       s_ids.push_back(created);
       return created;
   }  

private:
   ObjectID()
   {
      // as before
   }
};
链接地址: http://www.djcxy.com/p/96376.html

上一篇: 最新创建的类实例的静态类成员

下一篇: 通过静态指针访问成员变量实例