【问题标题】:operator -> or ->* applied to "const std::weak_ptr" instead of to a pointer typeC/C++运算符 -> 或 ->* 应用于“const std::weak_ptr”而不是指针类型C/C++
【发布时间】:2021-12-15 13:52:08
【问题描述】:

在一个 lambda 函数中,我试图使用 weak_ptr 来访问所有成员函数和变量,而不是这个,但我收到了这个错误:

运算符 -> 或 ->* 应用于“const std::weak_ptr”而不是指针类型

【问题讨论】:

  • std::weak_ptr 有const operator->() 吗?正如错误消息所说,也许您的意思是使用(智能)指针类型?

标签: c++ weak-ptr


【解决方案1】:

std::weak_ptr<T> 按照设计安全地指代一个可能存在也可能不存在的对象。它不提供operator->operator*,因为您必须确保对象仍然存在才能尝试访问它。

要访问std::weak_ptr 引用的对象,首先调用lock(),它会返回std::shared_ptr。然后,您需要检查 std::shared_ptr 是否引用了一个对象。如果是这样,那么该对象是可以安全访问的,并且在返回的指针被销毁之前不会被删除(因为它仍然存在std::shared_ptr)。如果不是,则 std::weak_ptr 指的是您无法再访问的已破坏对象。

Example

#include <memory>

class foo 
{
public:
    void bar(){}
};

void test(std::weak_ptr<foo> ptr)
{
    // Get a shared_ptr
    auto lock = ptr.lock();

    // Check if the object still exists
    if(lock) 
    {
        // Still exists, safe to dereference
        lock->bar();
    }
}

【讨论】:

  • 我认为if(auto lock = ptr.lock()) 也可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 2019-10-03
  • 1970-01-01
  • 2019-04-11
相关资源
最近更新 更多