有人可以向我解释为什么这段代码只打印"42"而不是"创建\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;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我在解决方案中使用不同的值尝试了这个代码,我总是得到"正确"的值,因此它似乎不是一个随机的幸运值.
小智 27
因为它表现出未定义的行为 - 您取消引用空指针.
当你说:
auto_ptr<MyClass> ptr;
Run Code Online (Sandbox Code Playgroud)
你创建一个不指向任何东西的autopointer.这相当于说:
MyClass * ptr = NULL;
Run Code Online (Sandbox Code Playgroud)
然后当你说:
cout<<ptr->solution()<<endl;
Run Code Online (Sandbox Code Playgroud)
你取消引用这个空指针.这样做在C++中是未定义的 - 对于您的实现,它似乎工作.
GMa*_*ckG 21
std :: auto_ptr不会自动为您创建对象.也就是说,ptr在main中,它被初始化为null.取消引用这是不明确的行为,你恰好幸运,结果是42.
如果您实际创建了该对象:
int main(int argc, char *argv[])
{
auto_ptr<MyClass> ptr(new MyClass);
cout << ptr->solution() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您将获得您期望的输出.