只能在栈上或者堆上创建对象
生活随笔
收集整理的這篇文章主要介紹了
只能在栈上或者堆上创建对象
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
只允許對象生成于堆內(nèi)?怎么理解?腫么辦?假如,手頭上有一個類Person,當(dāng)你在程序中寫下Person rn時,編譯器悄悄地做了兩件事:調(diào)用constructor構(gòu)造對象rn,而在彈棧時,調(diào)用destructor析構(gòu)對象rn。對象rn的構(gòu)造和析構(gòu)全部由編譯器負(fù)責(zé),這是棧的特性!諸所周知,對象rn生成于棧內(nèi)。而我們現(xiàn)在的要求是什么?“只允許對象生成于堆內(nèi)。”rn明顯違背了我們的要求,也就意味著它應(yīng)該被禁止。那這種 “坑爹型”的事情腫么辦呢?有人想說,只要讓Person的構(gòu)造函數(shù)或者析構(gòu)函數(shù)成為private就OK了。也許許多人真會有這樣的第一想法,假使那樣,咱再往下進(jìn)一步思考。如果那樣的話,這個類可以實現(xiàn)繼承嗎?No,即就是禁止繼承。另外,這個類允許其他類擁有它的對象嗎?No,即就是禁止包含。那怎么辦呢? 解決的方法也很簡單,解除繼承的副作用只需讓Person的析構(gòu)函數(shù)成為protected就可以了;解決內(nèi)含的副作用只需讓Test中的成員變量ps成為Person*類型并在Test的構(gòu)造/析構(gòu)函數(shù)中對成員變量做初始化和釋放操作就可以了。本例完整的代碼如下所示。
#include<iostream>
using namespace std;class Person
{
public:Person(){cout<<"Con()"<<endl;}Person(int x){a = x;cout<<"Con(x)"<<endl;}void Destroy(){delete this;}protected:~Person(){cout<<"Des"<<endl;}
private:int a;
};class Student:public Person
{};class Test
{
public:Test(){ps = new Person(); //堆上對象
}~Test(){ps->Destroy();}
private:Person *ps;
};void main()
{Test t1;
}
轉(zhuǎn)載自:http://www.cnblogs.com/Braveliu/archive/2013/01/06/2847475.html
C++中存放變量的地方有三個,分別是全局/靜態(tài)變量存儲區(qū),局部變量存儲區(qū) 即棧,new存放的變量存放在堆上,解題的思路是: 如果只在棧上創(chuàng)建對象則禁止在堆上創(chuàng)建,重寫operator new 和operator delete 如果只在堆上創(chuàng)建對象則把析構(gòu)函數(shù)定義為私有的,但是一定要定義一個函數(shù)把new的 對象刪除掉 void distory () const {delete this;} #include <iostream> using namespace std;class A { public:A(){cout<<"dhjj"<<endl;}void distory () const //通過公有接口訪問私有的析構(gòu)函數(shù){delete this;}private :~A(){ cout<<"this";}}; int main() {A* a=new A;a->distory();return 0; } 只能在棧上創(chuàng)建對象 #include <iostream> using namespace std;class A { public:A(){cout<<"dhjj"<<endl;}~A(){ cout<<"this";} private:void* operator new (size_t t); void operator delete(void *ptr); }; int main() {A* a=new A;A a;return 0; }轉(zhuǎn)載自:http://blog.csdn.net/acdnjjjdjkdckjj/article/details/5633611
轉(zhuǎn)載自:http://www.cnblogs.com/Braveliu/archive/2013/01/06/2847475.html
?
只能在堆上創(chuàng)建對象C++中存放變量的地方有三個,分別是全局/靜態(tài)變量存儲區(qū),局部變量存儲區(qū) 即棧,new存放的變量存放在堆上,解題的思路是: 如果只在棧上創(chuàng)建對象則禁止在堆上創(chuàng)建,重寫operator new 和operator delete 如果只在堆上創(chuàng)建對象則把析構(gòu)函數(shù)定義為私有的,但是一定要定義一個函數(shù)把new的 對象刪除掉 void distory () const {delete this;} #include <iostream> using namespace std;class A { public:A(){cout<<"dhjj"<<endl;}void distory () const //通過公有接口訪問私有的析構(gòu)函數(shù){delete this;}private :~A(){ cout<<"this";}}; int main() {A* a=new A;a->distory();return 0; } 只能在棧上創(chuàng)建對象 #include <iostream> using namespace std;class A { public:A(){cout<<"dhjj"<<endl;}~A(){ cout<<"this";} private:void* operator new (size_t t); void operator delete(void *ptr); }; int main() {A* a=new A;A a;return 0; }轉(zhuǎn)載自:http://blog.csdn.net/acdnjjjdjkdckjj/article/details/5633611
?
轉(zhuǎn)載于:https://www.cnblogs.com/leijiangtao/p/4495185.html
總結(jié)
以上是生活随笔為你收集整理的只能在栈上或者堆上创建对象的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cookie的利弊以及与web stor
- 下一篇: strlen 与 sizeof