与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);
}
既然std::shared_ptr<Teacher> teacher
已经是shared_ptr了,这里不允许teacher.shared_from_this()
吗? 如果没有,如何正确初始化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);
}
它会运行正常。
请注意,我不建议将其作为重构。构造函数应尽可能完全初始化对象。看看你的代码,在我看来,你可能想考虑重新构建它,有点激进。你真的需要所有这些交叉引用的共享指针吗?
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- 如何将enable-if与模板参数和参数包一起使用
- 如何将PERF_AMPLE_READ与mmap一起使用
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 程序崩溃并显示"std::out_of_range"错误
- 如何将C++中的库和头与MinGW一起使用
- 为什么gmp会在这里与"invalid next size"重新定位一起崩溃?
- C++ 将 setmode 与 _O_U8TEXT 一起使用来处理 unicode 时崩溃
- QT项目在配置文件上崩溃,与发布和调试器一起运行
- 当程序与符号名称一起崩溃时,输出呼叫堆栈
- C++无锁队列与多个线程一起崩溃
- 与boost::property_tree XML解析器一起使用时,boost::协同程序库崩溃
- 自定义分配器有时会与stl向量一起崩溃
- 将GSL与Qt一起使用时崩溃
- 与shared_ptr一起崩溃
- PInvoke x64与.Net 4.0一起崩溃
- Strcpy与strchr一起使用时崩溃
- 基本的OpenGL程序崩溃,但与gdb一起工作