c++ - 为什么这段代码只打印 42?

标签 c++ gcc auto-ptr

有人可以向我解释为什么这段代码只打印“42”而不是“created\n42”吗?

#include <iostream>
#include <string>
#include <memory>

using namespace std;

class MyClass
{
public:
    MyClass() {cout<<"created"<<endl;};
    int solution() {return 42;}
    virtual ~MyClass() {};
};

int main(int argc, char *argv[])
{
    auto_ptr<MyClass> ptr;
    cout<<ptr->solution()<<endl;
    return 0;
}

顺便说一句,我在解决方案中用不同的值尝试了这段代码,我总是得到“正确”的值,所以它似乎不是一个随机的幸运值。

最佳答案

因为它表现出未定义的行为 - 您取消引用空指针。

当你说:

 auto_ptr<MyClass> ptr;

你创建了一个不指向任何东西的自动指针。这相当于说:

MyClass * ptr = NULL;

然后当你说:

cout<<ptr->solution()<<endl;

您取消引用此空指针。这样做在 C++ 中是未定义的 - 对于您的实现,它似乎有效。

关于c++ - 为什么这段代码只打印 42?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1148328/

相关文章:

c++ - SFML loadFromFile 未定义引用

c++ - 如何将 boost::intrusive_ptr 与 boost::intrusive::list 一起使用?

c++ - Socket select() 在 Windows 下有效,在 Linux 下超时

c - GCC 内联汇编

python - fatal error : Python. h:没有这样的文件或目录

c++ - C:运行GSL函数

c++ - 返回指向类成员函数的指针

c++ - auto_ptr 会防止这种情况发生吗?

c++ - 这两个来源之间是否存在关于 `auto_ptr` 模板类的矛盾?

c++ - std::auto_ptr 与 std::tr1::shared_ptr