[英]Crash with shared_ptr
Can someone explain to me why the crash here?有人可以向我解释为什么这里崩溃吗?
#include <memory>
#include <functional>
struct Teacher : std::enable_shared_from_this<Teacher> {
struct Timetable;
std::shared_ptr<Timetable> timetable;
Teacher (int n) : timetable(std::make_shared<Timetable>(*this, n)) {}
};
struct Period {
std::shared_ptr<Teacher> teacher;
Period (const std::shared_ptr<Teacher>& t) : teacher(t) {}
};
struct Teacher::Timetable {
Teacher& teacher;
std::shared_ptr<Period> homeForm;
Timetable (Teacher& t, int n) : teacher(t), // Assume something is done with n.
homeForm( std::make_shared<Period>(teacher.shared_from_this()) ) {} // Crashes.
// homeForm( std::make_shared<Period>(std::shared_ptr<Teacher>(&teacher)) ) {} // Also crashes.
};
int main() {
std::shared_ptr<Teacher> teacher = std::make_shared<Teacher>(3);
}
Isn't teacher.shared_from_this()
allowed here since std::shared_ptr<Teacher> teacher
is a shared_ptr already?由于
std::shared_ptr<Teacher> teacher
已经是 shared_ptr ,因此这里是否允许teacher.shared_from_this()
? If not, how do I initialize homeForm
properly?如果没有,我该如何正确初始化
homeForm
?
The problem is that your code calls shared_from_this
before the std::shared_ptr<Teacher>
is fully constructed.问题是您的代码在
std::shared_ptr<Teacher>
完全构造之前调用了shared_from_this
。 It somehow makes sense that the Teacher
sub-object has to be constructed before the smart pointer is fully constructed.在完全构造智能指针之前必须构造
Teacher
子对象以某种方式是有道理的。
If you change the code like this,如果你像这样更改代码,
struct Teacher : std::enable_shared_from_this<Teacher> {
struct Timetable;
std::shared_ptr<Timetable> timetable;
Teacher() {}
void init(int n) { this->timetable = std::make_shared<Timetable>(*this, n); }
};
// Everything else unchanged
int main() {
std::shared_ptr<Teacher> teacher = std::make_shared<Teacher>();
teacher->init(3);
}
it will run fine.它会运行良好。
Note that I'm not recommending this as a refactoring.请注意,我不建议将此作为重构。 Constructors should fully initialize objects whenever possible.
构造函数应尽可能完全初始化对象。 Looking at your code, it seems to me that you might want to consider re-structuring it somewhat more radical.
看看你的代码,在我看来你可能想要考虑更激进地重新构建它。 Do you really need all this cross-referencing shared pointers?
你真的需要所有这些交叉引用共享指针吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.