Boost logo

Boost Users :

From: bringiton bringiton (kneeride_at_[hidden])
Date: 2006-07-13 21:38:03


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

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

---------------------------------
Example of usage for the type Test:

class Test {
public:
        Test() {;}
        Test(int p1) {;}
        Test(int p1, char p2) {;}
        Test(int p1, char p2, std::string p3) {;}
};

boost::shared_ptr<Test> p0 = NEW0(Test);
boost::shared_ptr<Test> p1 = NEW1(Test, 100);
boost::shared_ptr<Test> p2 = NEW2(Test, 100, 'a');
boost::shared_ptr<Test> p3 = NEW3(Test, 100, 'a', "hello");

---------------------------------
Is there a better way to do this? I would prefer to use a function
instead of a MACRO. But I don't think it is possible because it is not
know how many paramaters are in T's constructor.

// not sure how to do this (or whether possible)
// i am not sure how to implement the variable parameters // (hense
the .. in my syntax)
template <class T>
boost::shared_ptr<T> New(...)
{
        boost::shared_ptr<T> p(new T(...));
        return p;
}

Any ideas? I often have problems with the c++ syntax when creating my
own containers because i want to allocate T within the implementation
(instead of passing pointers and having the user manage the memory).


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