shared_ptr 崩溃
Crash with shared_ptr
谁能给我解释一下为什么会崩溃?
#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);
}
这里不允许 teacher.shared_from_this()
因为 std::shared_ptr<Teacher> teacher
已经是 shared_ptr 了吗?如果没有,我该如何正确初始化 homeForm
?
问题是您的代码在 std::shared_ptr<Teacher>
完全构建之前调用了 shared_from_this
。在智能指针完全构造之前必须构造 Teacher
子对象在某种程度上是有道理的。
如果你这样修改代码,
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);
}
它会 运行 没问题。
请注意,我不建议将此作为重构。构造函数应尽可能完全初始化对象。看看你的代码,在我看来你可能想要考虑更激进地重新构建它。您真的需要所有这些交叉引用共享指针吗?
谁能给我解释一下为什么会崩溃?
#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);
}
这里不允许 teacher.shared_from_this()
因为 std::shared_ptr<Teacher> teacher
已经是 shared_ptr 了吗?如果没有,我该如何正确初始化 homeForm
?
问题是您的代码在 std::shared_ptr<Teacher>
完全构建之前调用了 shared_from_this
。在智能指针完全构造之前必须构造 Teacher
子对象在某种程度上是有道理的。
如果你这样修改代码,
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);
}
它会 运行 没问题。
请注意,我不建议将此作为重构。构造函数应尽可能完全初始化对象。看看你的代码,在我看来你可能想要考虑更激进地重新构建它。您真的需要所有这些交叉引用共享指针吗?