[英]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.
当我通过静态的getter方法访问成员变量时,有时会得到错误的结果。
Code: 码:
hpp-file: HPP文件:
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: CPP文件:
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,另一线程调用
ObjectID::getID(id)->getShininess();
I don't always get 50, sometimes I get 1, and I am never changing m_shininess. 我并不总是得到50,有时我得到1,并且我从不改变m_shininess。 Any ideas?
有任何想法吗?
EDIT : 编辑 :
ObjectIDs are created in another class, which has a vector of ObjectIDs. ObjectID在另一个类中创建,该类具有ObjectID的向量。
m_objects.emplace_back();
Your vector holds shared_ptr, but you are emplacing raw pointers to ObjectID (this) into it. 您的向量包含shared_ptr,但是您将其中包含指向ObjectID(此)的原始指针。 Since shared_ptrs can be constructed from raw ones this compiles, but it probably isn't doing what you want it to.
由于shared_ptrs可以从原始代码构造而来,因此可以进行编译,但是它可能并没有按照您想要的去做。 In particular, you will wind up with wild pointers in that vector if an ObjectID gets destroyed though other means.
特别是,如果通过其他方法破坏了ObjectID,则在该向量中最终将使用野生指针。 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
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.