[英]What do you call a member function that follows a member function and how do I write one?
[英]what will happen if you do “delete this;” in a member function?
如果成員 function 嘗試delete this;
,比如在下面的class的構造函數中?
class A
{
public:
A(int);
~A();
int *pi;
}
A::A(int i)
{
delete this;
pi = new int(i);
}
A::~A()
{
delete pi;
}
這個C++ FAQ 條目很好地回答了這個問題,在這里重復:
只要你小心,object delete this
.
以下是我對“小心”的定義:
delete this
后訪問pi
違反了#3
壞事。 你可以delete this;
但這通常是一個非常糟糕的主意,一旦完成,您就無法觸摸任何成員變量或成員函數。
一般來說,從成員 function 內部調用delete this
是明確定義的,如果有一點風險的話。
但是從構造函數調用它可能是一個非常糟糕的主意(我不知道它是否定義明確)。 為什么你會想要那樣做?
您可以delete this
,但這假定該實例是使用new
創建的,並且您不再訪問該實例的任何成員。
在您的示例中,如果您這樣做,幾乎會發生相同的情況
class A
{
public:
A(int);
int *pi;
};
A::A(int i)
{
pi = new int(i);
}
int main()
{
A* p = new A(10);
delete p;
p->pi = new int; //bad stuff
//or
A a(20);
delete &a; //bad stuff
a.pi = new int; //more bad stuff
}
更糟糕的事情發生了,因為當你delete this
時, pi
成員被統一化,導致析構函數試圖刪除一個懸空指針。
1) delete 運算符僅適用於使用 new 運算符分配的對象。 如果 object 是使用 new 創建的,那么我們可以刪除它,否則行為未定義。
class A {
public:
void fun(){
delete this;
}
};
int main(){
/* Following is Valid */
A *ptr = new A;
ptr->fun();
ptr = NULL // make ptr NULL to make sure that things are not accessed using ptr.
/* And following is Invalid: Undefined Behavior */
A a;
a.fun();
return 0;
}
2)一旦刪除完成,刪除后object的任何成員都不應訪問。
class A {
int x;
public:
A() { x = 0;}
void fun() {
delete this;
/* Invalid: Undefined Behavior */
cout<<x;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.