【发布时间】:2017-06-30 21:35:09
【问题描述】:
在我正在编写的程序中,我有一个创建和处理一些线程的类。构造完成后,this 的实例将被赋予另一个类的对象,线程将能够调用其成员函数。
我已经让它与原始指针一起工作(只需替换智能指针),但由于我可以访问智能指针,我尝试使用它们来代替。虽然进展不大。
一些搜索让我使用了shared_ptrs,所以这就是我想要做的:
Obj.hpp:
#pragma once
#include "Caller.hpp"
class Caller;
class Obj : std::enable_shared_from_this<Obj> {
public:
Obj(Caller &c);
void dothing();
};
Caller.hpp:
#pragma once
#include <memory>
#include "Obj.hpp"
class Obj;
class Caller {
public:
void set_obj(std::shared_ptr<Obj> o);
std::shared_ptr<Obj> o;
};
main.cpp:
#include <iostream>
#include <memory>
#include "Caller.hpp"
#include "Obj.hpp"
void Caller::set_obj(std::shared_ptr<Obj> o)
{
this->o = o;
}
Obj::Obj(Caller &c)
{
c.set_obj(shared_from_this());
}
void Obj::dothing()
{
std::cout << "Success!\n";
}
int main()
{
Caller c;
auto obj = std::make_shared<Obj>(c);
c.o->dothing();
}
运行此代码会导致抛出std::bad_weak_ptr,但我不明白为什么。由于obj 是shared_ptr,对shared_from_this() 的调用不应该有效吗?
用g++ main.cpp 和gcc 7.1.1 编译。
【问题讨论】:
-
请随意改写标题问题。还有很多其他的问题可以匹配,但我不知道还能叫什么。
标签: c++ c++11 smart-pointers