如何獲得一個C++執行個體自己的指標

來源:互聯網
上載者:User
有的時候,寫C++代碼的時候,初始化了一個執行個體(Instance),即用類的定義建立了一個對象。
由於某些原因,在一些其它地方也需要使用這個執行個體,當然不能再重新定義一個對象了。這個時候,唯有想辦法獲得之前那個對象的指標。當指標也不能成為傳遞參數的時候,怎麼辦呢?可以利用待用資料成員,用如下的方法定義一個對象。
class TestInstance { public: TestInstance(void); ~TestInstance(void);
public: static TestInstance* Instance(){ if(_instance == NULL){ _instance = new TestInstance(); } return _instance; } static void Release(){ if(_instance != NULL){ delete _instance; _instance = NULL; } } private: static TestInstance* _instance; } TestInstance* TestInstance::_instance = NULL;

我們就是通過static TestInstance* _instance這個待用資料成員來固定地指向對象本身的。這樣的設計,需要在初始化類的時候,用如下的方法進行初始化:
TestInstance _TestInstance = TestInstance::Instance();

通過這樣的方法,我們就能把_TestInstance執行個體自己的指標,存到自己的資料成員裡。
在我們需要一個TestInstance執行個體的地方,只要用下面的語句就可以獲得它的指標了:
TestInstance * TestInstance = TestInstance::Instance();

當然,記得在不需要對象的時候,手動release掉:
TestInstance::Release();

這個技巧在很多情形下很有用!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.