私はダングリングポインターの概念を実証しようとしているので、それにプログラムを書いています。
クラス変数としてポインターがあり、独自のコピーコンストラクターを記述していない場合、ダングリングポインターの概念につながる可能性があるとします。
暗黙のコピー コンストラクターは、要素のメンバーごとのコピー (浅いコピー) を行います。そのため、1 つのオブジェクトがスコープ外になると、ダングリング ポインターの問題が発生します。
では、ぶら下がっているポインターを示すために私が書いたこのプログラムは正しいですか? 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;
}