home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!igor!thor!rmartin
- From: rmartin@thor.Rational.COM (Bob Martin)
- Newsgroups: comp.lang.c++
- Subject: Re: Avoiding returning references to Temporaries
- Message-ID: <rmartin.715870053@thor>
- Date: 7 Sep 92 12:47:33 GMT
- References: <lakldtINN17n@alnitak.usc.edu>
- Sender: news@Rational.COM
- Lines: 71
-
- coller@alnitak.usc.edu (Lee D. Coller) writes:
- [...]
-
- |The idea is that the member function D::getA() would be able to construct a
- |B or C and return it to the caller as an A. Because of the semantics, most
- |likely D::getA() will have to create a temporary, so just returning a
- |reference to some pre-existing B or C will not work.
-
- [...]
-
- |The best solution I could come up with is to create another class to handle
- |managing a pointer to A such as the following.
-
- [...example removed...]
-
- |My question is, I would like to be able to do this without having A handle
- |reference counting. Can anyone think of a good method? Am I overlooking
- |some simple, elegant solution? Also, is this what is referred to as a
- |"Smart pointer class?"
-
- Take a look at "Advanced C++ Programming Styles and Idioms" by James
- O. Coplien in the section entitled "Envelope Classes and Delegated
- Polymorphism". Here he talks about your problem and provides a
- solution.
-
- The idea is to provide class A with a A* member, and a member
- functions that can determine whether a B or C is needed. The needed
- class is placed in the A* pointer of the A object. All other method
- calls of the A objects are explicitly deferred to the A* object.
-
- For example:
-
- class A
- {
- public:
- A() {itsA = 0;}
- A(some criteria)
- {
- if (some criterion)
- itsA = new B(...);
- else
- itsA = new C(...);
- }
-
- virtual ~A() {delete itsA;}
-
- virtual int DoSomething(int x) {return itsA->DoSomething(x);}
-
- private:
- A* itsA;
- };
-
- class B : public A { public: B(); int DoSomething(int);};
- class C : public A { public: C(); int DoSomething(int);};
-
- Now, whenever you construct an A object, whether from the heap, or on
- the stack, or even statically; if you supply a criterion, the
- appropriate B or C will be silently constructed and saved by the A
- object. When you invoke the methods of A (DoSomething), those methods
- are simply deferred to the saved B or C object. When the A object is
- destructed, the B or C is also automatically destroyed.
-
- This method works well, but has one glaring fault. A must know about
- B and C. If more derivatives of A are needed later, A must change to
- support them in its constructor.
-
- --
- Robert Martin Training courses offered in:
- R. C. M. Consulting Object Oriented Analysis
- 2080 Cranbrook Rd. Object Oriented Design
- Green Oaks, Il 60048 (708) 918-1004 C++
-