gpt4 book ai didi

c++ - 弱指针分配失败

转载 作者:行者123 更新时间:2023-11-30 00:35:27 26 4
gpt4 key购买 nike

我正在尝试将 shared_ptr 指向自身内部结构的父节点。从这种数据类型派生时,我希望将父指针强制转换为派生类型。

这是我尝试使用的一段代码。

#include <iostream>

#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/make_shared.hpp>
using boost::shared_ptr;
using boost::weak_ptr;
using boost::dynamic_pointer_cast;
using boost::make_shared;

struct A
{
weak_ptr<A> parent;
int i;
virtual ~A() {}
};

struct B : virtual A
{
int j;
virtual ~B() {}
};

int main(int argc, char *argv[])
{
B a, b;
a.i = 1;
a.j = 2;
b.i = 4;
b.j = 8;

b.parent = weak_ptr<B>(make_shared<B>(a));
// ^^^
// The problem is here, not where I had
// thought it was earlier.

shared_ptr<B> pb;
if (pb = dynamic_pointer_cast<B>(b.parent.lock()))
{
// This is the code block that is intended to run
// but the control does not flow here.
std::cout << "b's parent: " << pb->i << ' '
<< pb->j << "\n";
}
else
{
std::cout << "Could not lock shared pointer or Pointer Null" << "\n";
}

return 0;
}

输出“失败”并显示以下消息

Could not lock shared pointer or Pointer Null

请解释行为

更新:

  1. 我从解释中了解到它实际上是误导性的,因此我更改了标题。

  2. 对我来说,以下 comment来自@Igor 最好的解释。

make_shared<B>(a) creates a temporary shared_ptr, which is destroyed at the semicolon. You assign it to weak_ptr - but weak_ptr alone doesn't keep the object alive

最佳答案

b.parent = weak_ptr<B>(make_shared<B>(a));

在这一行你创建了一个 shared_ptr,它死在了同一行。

weak_ptr 仅存储对它的弱引用,因此它不算作递增计数器的普通引用。

因此,当您使用 weak_ptrlock 方法时,它会返回一个空的 shared_ptr

关于c++ - 弱指针分配失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35016879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com