home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!news.mentorg.com!sdl!not-for-mail
- From: adk@Warren.MENTORG.COM (Ajay Kamdar)
- Newsgroups: comp.lang.c++
- Subject: Re: >>>>>>>> Is it possible to use 'delete this' ?
- Date: 31 Dec 1992 10:47:06 -0500
- Organization: Mentor Graphics Corp. -- IC Group
- Lines: 47
- Message-ID: <1hv4lqINN2fg@ajay.Warren.MENTORG.COM>
- References: <ssimmons.725636801@convex.convex.com> <796@ulogic.UUCP>
- NNTP-Posting-Host: ajay.warren.mentorg.com
-
- In article <796@ulogic.UUCP> hartman@ulogic.UUCP (Richard M. Hartman) writes:
- >
- >Is it possible, within the definition of a class, to ensure that
- >the object may only be successfully created by "new" and not
- >by a simple declaration?
- >
- >e.g.
- >
- > Object *p = new Object; // ok
- > Object O; // fails
- >
- >
-
- Yes, this is possible. Make the destructor of the class private. That
- will prevent users of the class from creating objects on the stack
- (attempts to create such an object on the stack will result in a compile
- time error.) A side effect of making the destructor private is that the
- object cannot be deleted directly; a member function to perform delete
- takes care of that problem.
-
- Example:
-
- class A {
- public:
- A() {}
- void free() {delete this;} // delete the object
- private:
- ~A() {} // will prevent A objects from being created on the stack
- };
-
- int main()
- {
- A a1; // compile time error
- A *a2 = new A; // ok
- delete a2; // compile time error
- a2->free(); // ok. deletes object.
- return 0;
- }
-
-
- - Ajay
-
- --
- I speak for none but myself.
-
- Ajay Kamdar Email : ajay_kamdar@mentorg.com
- Mentor Graphics, IC Group (Warren, NJ) Phone : (908) 580-0102
-