Boost logo

Boost Users :

From: Zolenko Yevgeniy (zolenkoe_at_[hidden])
Date: 2006-07-15 01:17:16


bringiton> I'm trying to define a MACRO that creates a shared_ptr and hides
bringiton> memory allocation. Here is what i have so far:

bringiton> #define NEW0(T) boost::shared_ptr<T>(new T());
bringiton> #define NEW1(T, p1) boost::shared_ptr<T>(new T(p1));
bringiton> #define NEW2(T, p1, p2) boost::shared_ptr<T>(new T(p1, p2));
bringiton> #define NEW3(T, p1, p2, p3) boost::shared_ptr<T>(new T(p1, p2, p3));

There is something wrong in the idea.

I mean from the design point of view. I think you should either trust your
users to know enough about shared pointers so as not to screw up memory
allocation (I am paranoid in this regard too though :)). Or you should hide
the shared pointer altogether.

So this:

> boost::shared_ptr<Test> p0 = NEW0(Test);

Will become something like this (and make all the constructors
private):

Test::Ptr p0 = Test::Allocate();

That requires more work, but it does fully enforce the contract.

If you maintain that consistently, throughout all you code, you
will have the control you desire. Down to transparent use of custom
allocators.

A wrapper (macro or else) just to ease the use of shared pointers is
pointless, since it does nothing to force its usage, and more often
than not, you will see it bypassed because of some momentary inconvenience.

Then, all of a sudden, you decide to allocate memory on a user's newly
installed brain implant (instead of old microchip), you modify you
macro or whatnot to use custom allocators (since new/delete used by
shared pointer are working with the old one), but in all the weird
places it would not be used. The head will explode then.

That is, however you do it, there should be either total freedom or
total control.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net