在我写的程序中,我有一个创建和处理一些线程的类。构造之后,这个实例将被赋予另一个类的对象,线程将能够调用它的成员函数。
我已经使用原始指针(只需替换智能指针),但由于我可以访问智能指针,我尝试使用它们。虽然没有太大进展。
有些搜索让我使用了shared_ptr
s,所以这就是我要做的事情:
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
进行编译。
答案 0 :(得分:2)
shared_from_this
仅在用共享指针包装后才能正常工作。
在构造点上,还没有指向你的共享指针。因此,在构造函数完成之后,您才能shared_from_this
。
解决这个问题的方法是旧的“虚拟构造函数”技巧。 1
class Obj : std::enable_shared_from_this<Obj> {
struct token {private: token(int){} friend class Obj;};
public:
static std::shared_ptr<Obj> create( Caller& c );
Obj(token) {}
};
inline std::shared_ptr<Obj> Obj::create( Caller& c ) {
auto r = std::make_shared<Obj>(token{0});
c.set_obj(r);
return r;
}
然后在测试代码中:
Caller c;
auto obj = Obj::create(c);
c.o->dothing();
1 虚拟构造函数既不是虚拟构造函数也不是构造函数。