为什么这段代码只打印42? [英] Why does this code only print 42?

查看:146
本文介绍了为什么这段代码只打印42?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人请解释一下为什么这段代码只打印42而不是created\\\
42?

Could somebody please explain to me why does this code only print "42" instead of "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;
}



我试了这个代码在解决方案不同的值,我总是得到

BTW I tried this code with different values in solution and I always get the "right" value, so it doesn't seem to be a random lucky value.

推荐答案

因为它展现未定义的行为 - 你取消引用一个空指针。

Because it exhibits undefined behaviour - you dereference a null pointer.

当你说:

 auto_ptr<MyClass> ptr;

您创建一个自动指向器,不指向任何东西。这相当于说:

you create an autopointer which doesn't point to anything. This is equivalent to saying:

MyClass * ptr = NULL;

然后当您说:

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

您将引用此空指针。这在C ++中是未定义的 - 对于你的实现,它似乎工作。

you dereference this null pointer. Doing that is undefined in C++ - for your implementation, it appears to work.

这篇关于为什么这段代码只打印42?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆