为什么在锁定weak_ptr时出现访问冲突?
Why am I getting an access violation when locking a weak_ptr?
我有一个std::weak_ptr。在尝试使用底层对象之前,我锁定它以获得shared_ptr:
auto foo_sharedptr = foo_weakptr.lock();
if (foo_sharedptr != nullptr)
{
// do stuff with foo
}
通常这很好。但是,有时我在调用lock时遇到访问冲突:
Unhandled exception at 0x00007FF91F411BC3 (My.dll) in My.exe:
0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
我的猜测是底层指针已被删除,但我对weak_ptr的理解是,在这种情况下,lock应该返回一个nullptr。我用错类型了吗?如果不是,我应该如何调试它?
EDIT:虽然被赞,但这似乎不是正确的答案,抱歉:
http://en.cppreference.com/w/cpp/memory/shared_ptr/operator_cmptemplate< class T >
bool operator==( const shared_ptr<T>& lhs, std::nullptr_t rhs );
(7) (since C++11)
template< class T >
bool operator!=( const shared_ptr<T>& lhs, std::nullptr_t rhs );
(9) (since C++11)
7) !韩
9) (bool) lh
…破碎的实现? ?真的不知道。
测试gcc -std=c++11:(取自http://en.cppreference.com/w/cpp/memory/weak_ptr并改编)
#include <iostream>
#include <memory>
std::weak_ptr<int> gw;
void f()
{
auto spt = gw.lock();
if (spt != nullptr) {
std::cout << *spt << "n";
}
else {
std::cout << "gw is expiredn";
}
}
int main()
{
{
auto sp = std::make_shared<int>(42);
gw = sp;
f();
}
f();
}
输出如预期:
<>之前42Gw已过期之前必须在别处
原始:
简而言之:将其检查为bool,不要与nullptr进行比较(这将尝试在nullptr上使用rhs = shared_ptr失败的lhs.get() == rhs.get()
):
auto foo_sharedptr = foo_weakptr.lock();
if (foo_sharedptr)
{
// do stuff with foo
}
参见文档:
#include <iostream>
#include <memory>
#include <thread>
void observe(std::weak_ptr<int> weak)
{
std::shared_ptr<int> observe(weak.lock());
if (observe) {
std::cout << "tobserve() able to lock weak_ptr<>, value=" << *observe << "n";
} else {
std::cout << "tobserve() unable to lock weak_ptr<>n";
}
}
int main()
{
std::weak_ptr<int> weak;
std::cout << "weak_ptr<> not yet initializedn";
observe(weak);
{
std::shared_ptr<int> shared(new int(42));
weak = shared;
std::cout << "weak_ptr<> initialized with shared_ptr.n";
observe(weak);
}
std::cout << "shared_ptr<> has been destructed due to scope exit.n";
observe(weak);
}
相关文章:
- 写入位置0x0000000C时发生访问冲突
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 链表中写入访问冲突的未知原因
- C++中的openCV Mat访问冲突
- C++尝试深度复制唯一指针时出现内存访问冲突
- C++ 中动态二维数组的访问冲突
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 写入访问冲突异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 读取访问冲突.这0xCDCDCDCD
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 插入数组时违反写访问冲突
- 使用 ReadProcessMemory 获取字符串值的访问冲突
- 尝试通过共享指针使用变量时读取访问冲突
- 堆栈上的 C++ 访问冲突写入异常
- 引发异常:写访问冲突. temp 为 nullptr
- 将静态字符数组中的字符分配给动态分配的字符数组 - 访问冲突
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 读取访问冲突_First为空Ptr