通过智能指针调用另一个类的成员函数
Calling another class` member functions via smart pointers
在我正在编写的程序中,我有一个创建和处理一些线程的类。构造后,将为其实例提供另一个类的对象,线程将能够调用其成员函数。
我已经让它与原始指针一起使用(只需替换智能指针(,但由于我可以访问智能指针,因此我尝试使用它们。虽然没有太大进展.
一些搜索导致我使用 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
编译。
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 虚拟构造函数既不是虚拟构造函数也不是构造函数。
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法