我是智能指针的新手,我试图绕过我的脑袋,为什么在取消引用运算符之后weak_ptr会过期.我以前测试的代码在这里:
#include <memory>
#include <iostream>
#include <vector>
using namespace std;
struct node
{
weak_ptr<node> parent;
shared_ptr<node> child;
int val;
};
shared_ptr<node> foo()
{
shared_ptr<node> a = make_shared<node>();
shared_ptr<node> b = make_shared<node>();
a->val = 30;
b->val = 20;
b->parent = a;
a->child = b;
return a;
}
int main()
{
shared_ptr<node> c = foo();
node d = *foo();
if (c->child->parent.expired())
{
cout << "weak ptr in c has expired." << endl;
}
if (d.child->parent.expired())
{
cout << "weak ptr in d …Run Code Online (Sandbox Code Playgroud) 我有一个简单的容器类,指向一个抽象类,我有函数来获取/设置容器类中的指针.更具体地说,这个类看起来像这样:
class Container
{
Abstract* thing;
public:
void set(Abstract &obj)
{
thing = &obj; //danger of dangling pointer
}
Abstract* get()
{
return thing;
}
};
Run Code Online (Sandbox Code Playgroud)
Abstract是一个抽象类.可以看出,存在悬挂指针的危险.我知道我可以制作一个对象的副本(新),然后指向它.但我无法创建抽象类的实例.有什么解决方案吗?
以下是更多信息:
类定义
class Abstract
{
public:
virtual void something() = 0;
};
class Base : public Abstract
{
int a;
public:
Base() {}
Base(int a) : a(a){}
virtual void something()
{
cout << "Base" << endl;
}
};
class Derived : public Base
{
int b;
public:
Derived() {}
Derived(int a, int …Run Code Online (Sandbox Code Playgroud)