Symbian Special Interest Group

Sig Is symbian special interest Group

« Get ready for the Open C ChallengeInside CBase class - six essential questions »

How to prevent object being created on stack

In Symbian, sometimes you don't want the user of your class to create the object of it on stack, because the stack resource is rare. Is there any way to do this? Yes.

What you should do is to make your destructor private, rather than public or protected. You can do like this:

class CTest : public CBase
{
private:
        ~CTest ();
}

Why only private, because if you make it protected, yes the object this class can't not be created on stack, but it's derived class can!

Then, if you want to create the object on stack, like

CTest test;

The compiler is gona complain, the error message is most probably like "Error 1 : 'CTest::~CTest' : cannot access private member declared in class 'CTest ". That's because the compiler will actually check if it can delete the object if it's created on stack, because it's compiler's business to take care of this. If you do like:

CTest* test

or

CTest* test = new (ELeave) CTest

It's gona be fine, because the only thing you put on the stack is just the pointer, compiler don't even have to call the destructor of the pointer.

Then, how do you delete the object whose destructor is private?? Just use delete operator is not going to work, because delete operator is not a part of the CTest class. So you have to provide a function which will delete the object itself. It's like:

void CTest::Release()
{ delete this; }

Since "delete this" is not a "good manner"(it works, but it's not recommended), you have to pay more attendtions when you use this. You have to make sure that the object is not created by "new[]". You have to make sure Release is the last function you call on this object, etc.

  • quote 1.三面翻
  • http://www.zz-hh.com/sanmianfan.htm
  • 换新面孔了,虽然有点陌生,但还是很喜欢的。。。
    [url=http://www.zz-hh.com/sanmianfan.htm]三面翻[/url]
    [url=http://www.kmtyn.com/solarpanel.htm]solar panel/solar panels[/url][url=http://www.kmtyn.com/solarpanels.htm]solar panel/solar panels[/url]
    [url=http://www.sdxtkj.com]打标机/激光打标机[/url]
  • 2008-11-12 11:28:23
  • quote 2.Google网站推广
  • http://www.91abc.cn
  • <A href="http://www.91abc.cn/">Google网站推广</a>
    <A href="http://www.91abc.cn/">Google网站优化</a>
    <A href="http://www.91abc.cn/">Google英文网站推广</a>
    <A href="http://www.91abc.cn/">Google左侧优化</a>
    <A href="http://www.91abc.cn/">Google左侧推广</a>
  • 2008-12-25 13:18:20

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

日历

最新留言

最近发表

Powered By Z-Blog 1.6 Final Build 60816

Copyright 2006-2007 SymbianSIG.com . All Rights Reserved.