我有以下代码框架。在 values
映射的生命周期之后,pValue
是否仍然可以访问?
class Value { /* ... */ };
enum Key { aKey /* , ... */ };
class ValueStorage
{
public:
ValueStorage() { /* calculate all kinds of values and store them */ }
// returns nullptr if not available
std::shared_ptr<Value> getValue(Key key)
{
auto it = values.find(key);
return it != values.end() ? shared_ptr<Value>(&it->second) : nullptr;
}
private:
std::map<Key, Value> values;
};
shared_ptr<Value> pValue;
{
ValueStorage values;
pValue = getValue(aKey);
}
assert (pValue.get()); // is the Value the shared_ptr refers to still alive ?
如果不是,我该如何避免这个问题?我可以更改 getValue 的实现吗?
或者万一我无法避免这个问题,是否应该返回一个裸指针以避免混淆其生命周期更好?
(我本可以通过返回一个值而不是一个指针来避免麻烦,但我更喜欢指针版本,因为它允许在值不可用的情况下返回 nullptr)
最佳答案
这将是一个问题,因为您正在构建 std::shared_ptr<Value>
在getValue()
根据从map中获取的元素地址,当map销毁时,其所有元素也将被销毁,则指针shared_ptr
持有变得悬空。
你可能 new
getValue()
中的新指针, shared_ptr
将delete
它终于。
std::shared_ptr<Value> getValue(Key key)
{
auto it = values.find(key);
return it != values.end() ? shared_ptr<Value>(new Value(it->second)) : nullptr;
}
并且不要返回裸指针,问题根本没有改变。
关于c++ - 指向对象数据成员的 shared_ptr 是否使数据成员在对象的生命周期之后保持事件状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35914292/