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