2
有人可以向我解释为什么在这里崩溃?崩溃与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
?
基本上,它是在'enable_shared_from_this'基础中设置'weak_ptr'的'shared_ptr'构造函数。所以你需要构建整个'shared_ptr'而不仅仅是'Teacher'。 –
Barry
谢谢。但在我的实际程序中,教师构造函数具有需要传递给Teacher :: Timetable构造函数的参数。这意味着init需要接收这些参数。我已经更新了我的问题。在main()中复制这些参数是唯一的方法吗?或者将这些参数存储在'Teacher'中,然后将它们传递给'init',尽管它们只是暂时的? – prestokeys
@prestokeys我不明白你为什么必须将它们传递给构造函数。但我会重复一遍,我不*广告使用'init'函数或这种编码风格。 – 5gon12eder