在下面的代码中,while ( !Ref.expired() );
快乐地优化为无限循环.如果代码行更改为while ( !Ref.lock() );
.一切都按预期工作.真的有两个问题:
1)当std::weak_ptr::expired()
访问内存隔离计数器时,编译器如何优化过期?
2)Ref.lock()
实际上是安全的,还是可以将其优化掉?
示例代码如下.
#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
class A
{
public:
A()
{
m_SomePtr = std::make_shared<bool>( false );
}
virtual ~A()
{
std::weak_ptr<bool> Ref = m_SomePtr;
m_SomePtr.reset();
// Spin (will be optimised into an infinite loop in release builds)
while ( !Ref.expired() );
}
std::shared_ptr<bool> GetPtr() const { return m_SomePtr; }
private:
std::shared_ptr<bool> m_SomePtr;
};
class B
{
public:
B( std::shared_ptr<bool> …
Run Code Online (Sandbox Code Playgroud)