小编Puf*_*Air的帖子

为什么std :: weak_ptr :: expired已经优化了?

在下面的代码中,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)

c++ multithreading shared-ptr visual-c++ c++11

32
推荐指数
1
解决办法
780
查看次数

标签 统计

c++ ×1

c++11 ×1

multithreading ×1

shared-ptr ×1

visual-c++ ×1