我试图展示悬空指针的概念,然后在上面写一个程序。
假设你有指针作为类变量并且你不编写你自己的拷贝构造函数那么它就会导致悬空指针的概念。
隐式复制构造函数执行元素的成员明智复制(浅复制)。因此,如果一个对象超出范围,则会导致悬空指针的问题。
我编写的这个程序是为了演示悬空指针是否正确? 当我在ideone.com上编译它并且它给出了运行时错误。
#include"iostream"
using namespace std;
#include<string.h>
class cString
{
int mlen;char* mbuff; //**pointer** is a member of class
public:
cString(char *buff) //copy buff in mbuff
{
mlen=strlen(buff);
mbuff=new char[mlen+1];
strcpy(mbuff,buff);
}
void display() //display mbuff
{
cout<<mbuff;
}
~cString()
{
cout<<"Destructor invoked";
delete[] mbuff; //free memory pointed by mbuff
}
};
int main()
{
cString s1("Hey");
{
cString s2(s1); //call default copy constructor(shallow copy)
s2.display();
} //destructor for object s2 is called here as s2 goes out of scope
s1.display(); //object s1.display() should be unable to display hey
return 0;
}