Skip to main content
gamedev.net
🔒 Locked

Preventing Stack Allocation

Started by daerid Apr 9, 2004 at 6:54 PM 4 replies 800+ views
Original Post
daerid
daerid
I don''t know if the thread title is accurate enough, so here''s what I want to do:
#include <iostream>

#include <string>

#include <stdexcept>

struct stack_alloc_error : public std::runtime_error
{
  stack_alloc_error() : runtime_error("Stack Allocation not allowed");
};

class SomeClass
{
  // What to put here?

};

int main(int argc,char* argv[])
{
  try
  {
    SomeClass* psc = new SomeClass; // <- this should work without error

    
    SomeClass sc; // <- This should throw a stack_alloc_error    

  }
  catch(std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }
}


daerid | Legends | Garage Games | Spirit | Hapy | Boost | Python | Google "Doomed to crumble, unless we grow, and strengthen our communication" - Maynard James Keenan, Tool
daerid@gmail.com
SiCrane
SiCrane
I don''t think you want this to be an exception, since allocating on the stack is fundamentally a compile time error. Detecing an error at runtime that could be detected at compile time is suboptimal. Consider instead this type of construct:

class OnHeapOnly {
public:
OnHeapOnly() {}
static void free(OnHeapOnly * ptr) { delete ptr; }
private:
~OnHeapOnly() {}
};

void f(void) {
OnHeapOnly a; // error

OnHeapOnly * ptr = new OnHeapOnly(); // ok

// ...

delete ptr; // error

OnHeapOnly::free(ptr); // fine

}
daerid
daerid
Ahhhhh yes. I see.
daerid@gmail.com
stushock
stushock
Is would like to prevent stack allocation of a hierarchy of classes. Is there any way to put code in the base class to prevent derived classes from being stack allocated (without putting extra code in the child classes).
Oxyd
Oxyd
I think this is not exactly what you want, but it may work for you:


class OnHeap {
public:
.... //some useful stuff


void *operator new (size_t) { return ::new Base; }
void operator delete (void *mem) { ::delete mem; }

protected: //allow the derived classes to call the constructor

OnHeap () {}
~OnHeap () {}
};

...

OnHeap o; //error

OnHeap *o = new OnHeap; //ok

delete o;


And as far as I know you can use the OnHeap''s version of new and delete for the derived classes... The only thing you need to do is to declare their constructors as protected.

Oxyd

- Unreadable code is code written on a piece of paper, but not the one, in which the programmer is using a space in the place you don''t.
- Real programmers aren''t afraid of goto
msn12b
msn12b
quote:
Original post by Oxyd
And as far as I know you can use the OnHeap''s version of new and delete for the derived classes... The only thing you need to do is to declare their constructors as protected.



Actually, you just need to protect the destructor, either via protected: or private:.

MSN

angryzenmaster @ livejournal

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.