How to Prevent an Object Being Created on the Heap

How to prevent an object being created on the heap?

Nick's answer is a good starting point, but incomplete, as you actually need to overload:

private:
void* operator new(size_t); // standard new
void* operator new(size_t, void*); // placement new
void* operator new[](size_t); // array new
void* operator new[](size_t, void*); // placement array new

(Good coding practice would suggest you should also overload the delete and delete[] operators -- I would, but since they're not going to get called it isn't really necessary.)

Pauldoo is also correct that this doesn't survive aggregating on Foo, although it does survive inheriting from Foo. You could do some template meta-programming magic to HELP prevent this, but it would not be immune to "evil users" and thus is probably not worth the complication. Documentation of how it should be used, and code review to ensure it is used properly, are the only ~100% way.

limit the creation of object on heap and stack in C++

To prevent accidental creation of an object on the heap, give it private operators new. For example:

class X {
private:
void *operator new(size_t);
void *operator new[](size_t);
};

To prevent accidental creation on the stack, make all constructors private, and/or make the destructor private, and provide friend or static functions that perform the same functionality. For example, here's one that does both:

class X {
public:
static X *New() {return new X;}
static X *New(int i) {return new X(i);}
void Delete(X *x) {delete x;}
private:
X();
X(int i);
~X();
};

Is it possible to prevent stack allocation of an object and only allow it to be instantiated with 'new'?

One way you could do this would be to make the constructors private and only allow construction through a static method that returns a pointer. For example:

class Foo
{
public:
~Foo();
static Foo* createFoo()
{
return new Foo();
}
private:
Foo();
Foo(const Foo&);
Foo& operator=(const Foo&);
};

C++, preventing class instance from being created on the stack (during compiltaion)

When myclass reaches the end of its scope (the next }) the compiler calls the destructor to free it from the stack. If the destructor is private, however, then the destructor cannot be accessed, so the class cannot be placed on the stack.

I don't like the look of delete this. In general I think objects should not destroy themselves. Perhaps a better way is to have a private constructor for your class then use a static function to create an instance.

// In class declaration...
static MyClass* Create()
{
return new MyClass(); // can access private constructor
}

// ...

MyClass myclass; // illegal, cannot access private constructor

MyClass* pMyClass = MyClass::Create();
delete pMyClass; // after usage

How to prevent others create a new instance of a class on heap?

I think the best you can do is to declare a private operator new (I can't recall if this is needed but you'll probably want to do all three: normal, array, and placement) in your base class. The user can still get around this by creating their own operator new in the Derived class but at least they have to think about it and actively work to subvert your intention.

If you're worried about non-accidental problems with creating your class on the heap (for example malicious developers of child classes), C++ is not the language for this project. It's powerful and has lots of places where your have to rely on your end-programmers not bypassing the intentions.

Object creation on the stack/heap?

Actually, neither statement says anything about heap or stack. The code

Object o;

creates one of the following, depending on its context:

  • a local variable with automatic storage,
  • a static variable at namespace or file scope,
  • a member variable that designates the subobject of another object.

This means that the storage location is determined by the context in which the object is defined. In addition, the C++ standard does not talk about stack vs heap storage. Instead, it talks about storage duration, which can be either automatic, dynamic, static or thread-local. However, most implementations implement automatic storage via the call stack, and dynamic storage via the heap.

Local variables, which have automatic storage, are thus created on the stack. Static (and thread-local) objects are generally allocated in their own memory regions, neither on the stack nor on the heap. And member variables are allocated wherever the object they belong to is allocated. They have their containing object’s storage duration.

To illustrate this with an example:

struct Foo {
Object o;
};

Foo foo;

int main() {
Foo f;
Foo* p = new Foo;
Foo* pf = &f;
}

Now where is the object Foo::o (that is, the subobject o of an object of class Foo) created? It depends:

  • foo.o has static storage because foo has static storage, and therefore lives neither on the stack nor on the heap.
  • f.o has automatic storage since f has automatic storage (= it lives on the stack).
  • p->o has dynamic storage since *p has dynamic storage (= it lives on the heap).
  • pf->o is the same object as f.o because pf points to f.

In fact, both p and pf in the above have automatic storage. A pointer’s storage is indistinguishable from any other object’s, it is determined by context. Furthermore, the initialising expression has no effect on the pointer storage.

The pointee (= what the pointer points to) is a completely different matter, and could refer to any kind of storage: *p is dynamic, whereas *pf is automatic.

How to stop a object being created in a loop from begin destroyed in c++?

The objects are being destroyed because they are local to the loop (created on the stack). Instead you have to use the keyword new for it to be created on the heap. Try doing this

something & aSomething = *new something;

SimpleClass * anObject = new SimpleClass(i);

aSomething.object = anObject;

array[i] = aSomething;

put this in the for loop instead of what you have

Also I would suggest using new instead of malloc to create your array since you are using c++

How to improve application to avoid heap space issues

I would start out by profiling your application and looking for memory hot spots by using the jvisualvm (part of the JDK). This will give you and indication of how large your objects are and what method calls are resulting in high memory use. It will also tell you how long your objects are haning around in memory which is generally a good starting point as you want to reduce scope to be as short as possible.

The next step is to identify commonalities in your objects either by refining your design or by implementing a cache. If you're loading data from a fixed store then you could use softreferences so as the JVM runs out of heap these objects will be GCed (if your making changes to these objects you will obviously need to persist them before removing the hard reference). Then if they are needed again your application will simply need to reload them from the backing store (DB, files or whatever).

Make sure you know how GC works and understand your object references:

  • Strong/Direct
  • Soft
  • Weak
  • Phantom

Here are a few good articles which explain references and GC:

http://www.java-tips.org/java-se-tips/java.util/using-weakhashmap-for-listener-lists.html

http://pawlan.com/monica/articles/refobjs/

http://www.kdgregory.com/index.php?page=java.refobj



Related Topics



Leave a reply



Submit