how can we restrict object creation on heap ?

S

shaanxxx

how can we restrict object creation on heap ?

soln1: overload new

any other way to do this ?
 
K

kwikius

shaanxxx said:
how can we restrict object creation on heap ?

soln1: overload new

any other way to do this ?

The only way I can think is to create your own memory pool and check
the address of the object is in it in the constructor. OTOH maybe you
can get at the heap top and bottom pointers for a similar result. Not
sure how to do that portably though.

regards
Andy Little
 
W

wkaras

shaanxxx said:
how can we restrict object creation on heap ?

I think you mean require class instances to be in heap.
soln1: overload new

Wrong, unless I misunderstood above.
any other way to do this ?

Easy, portable way: make all constructors
private, then provide a static member that
creates an instance on the stack, and
returns a pointer, like X::make_inst for
example:

static X * make_inst() { return(new X); }
 
K

kwikius

I think you mean require class instances to be in heap.


Wrong, unless I misunderstood above.


Easy, portable way: make all constructors
private, then provide a static member that
creates an instance on the stack, and
returns a pointer, like X::make_inst for
example:

static X * make_inst() { return(new X); }

You pay quite a high price just to ensure construction only on the
heap...

class X{
private:
X(){}
friend X* make_X(){return new X();}
protected:
virtual void f(){};
};

class Y : protected X{
public:
Y() : X(){}
void f(){}
};

int main()
{
Y y;
}


regards
Andy Little
 
B

bjeremy

I think you mean require class instances to be in heap.


Wrong, unless I misunderstood above.


Easy, portable way: make all constructors
private, then provide a static member that
creates an instance on the stack, and
returns a pointer, like X::make_inst for
example:

static X * make_inst() { return(new X); }

An alternative:

If the objective is to *solely* limit object creation to use the heap,
it may be easier at times to declare the destructor as private instead
of the constructor. If the class has many constructors, you must
remember to make all the constructors private. This also includes both
the copy and default constructors if they would otherwise be generated
by the compiler.

If you just declare the destructor private, all you need is to declare
one method private, and provide a psuedo-destructor that simply deletes
the object...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top