gpt4 book ai didi

c++ - 为什么不使用 NULL autoPtr 终止程序?

转载 作者:太空狗 更新时间:2023-10-29 23:25:51 26 4
gpt4 key购买 nike

#include<iostream>
using namespace std;
template<class T>
class autoPtr
{
public:
autoPtr(T* ptr)
{
cout<<"autoPtr ctr"<<endl;
loc=ptr;
}

autoPtr()
{
loc=NULL;
cout<<"autoPtr dflt ctr"<<endl;
}
~autoPtr()
{
cout<<"autoPtr dtr"<<endl;
delete loc;
}
//assignment operator
autoPtr& operator=(autoPtr& rRef)
{
cout<<"autoPtr assignment operator"<<endl;
loc=rRef.loc;
rRef.loc=NULL;
return *this;

}
T* operator->()
{
cout<<"address -"<<loc<<endl;
return loc;
}

private:
T* loc;
};

class base
{
public:
base()
{
cout<<"base ctr"<<endl;
}
~base()
{
cout<<"base dtr"<<endl;
}
void printHello(int i)
{
cout<<"HELLO : "<<i<<endl;
}
};

int main()
{
autoPtr<base> ptr(new base());
autoPtr<base> ptr1;
ptr1=ptr;
ptr1->printHello(1);
ptr->printHello(2); //should make the program terminate, but not so ?
}

问题是:

ptr->printHello(2);

应该让程序终止,但它没有。为什么不?

最佳答案

因为你走运了。您的程序导致未定义的行为

ptr1 = ptr

此代码为第一个 auto_ptr 对象 ptr 分配 NULL 地址,为第二个对象 ptr1 分配一些非 NULL 地址,源对象在赋值过程中丢失引用 (=)。

执行语句时:

ptr->printHello(2);  

ptr 是一个 NULL 指针,取消引用 NULL 指针是未定义的行为

但由于在函数 printHello() 中您不访问任何类成员变量,因此它工作正常。向您的类添加一个成员变量,然后尝试在 printHello() 函数中访问它,您将看到它(很可能)崩溃

重要的是要注意,未定义的行为 意味着任何事情都可能发生,并且无法根据 C++ 标准中的语言规范来定义该行为。在这种情况下,它有效的事实并不能保证它总是有效,它仍然是一个未定义的行为。

关于c++ - 为什么不使用 NULL autoPtr 终止程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6992827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com