class plugin {
public:
enum RunStatus {
Running = 0
};
int test()
{
printf("test null shared ptr\n");
return 0;
}
};
int main()
{
std::shared_ptr<plugin> iter = NULL;
std::cout << iter->test() << std::endl; // 不会异常退出
std::shared_ptr<int> iterInt = NULL;
std::cout << *iterInt << std::endl; // 异常退出
return 0;
}
如果plugin类有成员变量,也会异常退出
该博客探讨了C++中智能指针`std::shared_ptr`的使用,展示了当尝试访问空指针时的行为差异。在示例中,`std::shared_ptr<plugin>`在调用成员函数时并未引发异常,而`std::shared_ptr<int>`及含有成员变量的`plugin`类在尝试解引用空指针时导致程序异常退出。这强调了智能指针在空指针处理上的安全性及其对空指针异常的处理方式。

2626

被折叠的 条评论
为什么被折叠?



