- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
#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/
尝试使用 AutoPtr 处理 const 指针: void LiveTimeConfig::setup(const AbstractConfiguration& cfg){ GetLogge
#include using namespace std; template class autoPtr { public: autoPtr(T* ptr) {
编辑:我应该提到,我正在查看 documentation for Boost's ptr_sequence_adapter 它声称他们的适配器适用于 template void push_back(
我是一名优秀的程序员,十分优秀!