我正在阅读 Scott Meyrses 的 C++ 并遇到以下代码:
class Lock {
public:
explicit Lock(Mutex *pm) // init shared_ptr with the Mutex
: mutexPtr(pm, unlock) // to point to and the unlock func
{
lock(mutexPtr.get()); // see Item15 for info on “get”
}
private:
std::tr1::shared_ptr<Mutex> mutexPtr; // use shared_ptr
}; // instead of raw pointer
在脚注中,他说代码不是异常安全的。所以在 his blog他建议修改calss的构造函数如下:
explicit Lock(Mutex *pm)
{
lock(pm);
mutexPtr.reset(pm, unlock);
}
尚不清楚为什么这段代码应该有效。我们在尚未初始化的 mutextPtr
上调用 reset 方法(我们从 ctor-initializer 中删除了条目)。为什么我们得不到谎言 Segmenetation fault
?
最佳答案
mutexPtr
未初始化。当你从初始化列表中遗漏一些东西时,它的默认构造函数将被调用,如果它有的话。 shared_ptr
有一个默认的构造函数,它将持有的指针设置为空(即没有对象被管理)。调用 reset
然后将其设置为管理 pm
。什么都没有被删除,因为什么都没有保留。即使在保留指针上调用了 delete
,在空指针上调用 delete
也是空操作,所以这不是问题。
关于c++ - RAII 对象 tr1 :shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31468423/