Click here to Skip to main content
15,885,979 members
Please Sign up or sign in to vote.
4.14/5 (3 votes)
See more:
I have two question here.

I want to

Q1. Restrict user to create memory on STACK only?
Q2. Restrict user to create memory on Heap only?


Please let me know if anybody has some ideas about these questions.

Thanks in Advance
Posted
Comments
CPallini 24-May-12 15:20pm    
Why?
--Carlo the curious.
Sergey Alexandrovich Kryukov 26-Feb-13 0:27am    
The question as is makes no sense. If the restriction is provided to some user, who is OP. What kind of code is being developed? Without this information (I doubt it exists though :-), there is nothing to talk about.
—SA
sourabhmehta 27-Feb-13 0:05am    
It totally makes sense.
If you can't appreciate somebodies answers. Please don't pollute the forums
Sergey Alexandrovich Kryukov 27-Feb-13 0:30am    
No, you please stop polluting the forum. When you are asked for clarification, you show only the claims and baseless accusations. Please be a reasonable person and stop it. If you don't like my comments, this is no excuse for fighting...
—SA
Sergey Alexandrovich Kryukov 26-Feb-13 19:57pm    
Please stop posting non-answers as "solution". It can give you abuse reports which eventually may lead to cancellation of your CodeProject membership.
Comment on any posts, reply to available comments, or use "Improve question" (above).
Also, keep in mind that members only get notifications on the post sent in reply to there posts.
—SA

It depends on what you define as "restricting a user". In C++ there is almost always a way around restrictions placed by language constructs. If you want to create a class that when properly used restricts the user to the respective memory resource, here is a way to do that:

(a) Only on stack: Define a custom operator new function in your class and throw an appropriate exception there. That doesn't give a warning at compile time, though.

Edit: As pointed out in the comment by Aesceal, declaring operator new as private will even give a comile time warning when someone tries to allocate an object of this class on the heap. So not only declare a custom operator new, but also make it private.

(b) Only on heap: Make the constructors protected or private and provide a public static function that creates an object of this class. In this function you use new to create an object of this kind. For symmetry reasons I would also provide a public static function for the deletion of such objects. By this technique the user can only use these two functions to create and destroy objects of this class.

Edit: Making the constructors protected will allow derived classes to override this behaviour; making it private will even prevent derived classes from being allocated on the heap.
 
Share this answer
 
v2
Comments
Aescleal 24-May-12 12:39pm    
Have -1 for missing that declaring new private stops heap allocation but have one back for suggesting symmetric functions for heap based only - I should have had that in my answer!
nv3 24-May-12 13:41pm    
Declaring operator new private in fact stops allocation on the heap and even gives a compile time error. Nice! Got my 5.
sourabhmehta 24-May-12 13:00pm    
Thanks for the reply.

1. First solution is acceptable here. Doing that or making a private new operator , we can achieve this.

2.This, i'm not in agreement with you. we can always create a parameterized constuctor. so i got a better solution to acheive this.... making destructor private shall work here. but doing this the question arrises. In this case how to deallocate memory? now to solution will be having a method say destroy doing (delete this) will also do that :)
Aescleal 24-May-12 13:09pm    
If you want to delete an object with a private destructor write a static member function of the class and do a delete in there. As it's a member of the class you can call private functions on objects. Or if you don't want a static then have a friend function - much the same effect either way, there are arguments for both.
nv3 24-May-12 13:55pm    
Regarding 2: To create an additional parameterized constructor you would have to derive from your class and the constructor in you original class would have to be protected. If you make the constructor of your original class private, even deriving will not allow you to define a parameterized constructor, because your derived class has no access right to the original constructor.

Your solution with the private destructor works nicely, though, as well.
For heap only use a private destructor and have a static member function of the class that does the delete for you. For stack only declare operator new private.

Cheers,

Ash

PS: Just realised that if someone really wants to get around private operator new they can just make sure that they use global operator new. Grrr.... And you have to declare array new private as well.

Edit: I'm talking complete bollocks, BRB when I've actually tested what I'm talking about!
Edit: Now speaking 50% less bollocks
 
Share this answer
 
v4
Please use the "Named Constructor Idiom".
See here : http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Named_Constructor[^]

For example, if you want allocate a memory only in heap :
class MyClass {
public:
    // The create() methods are the "named constructors":
   static MyClass* create() { return new MyClass(); }
    ...
private:
   // The constructors themselves are private or protected:
  MyClass();
   ...
}; 

//Now exist only one way to create a MyClass objects => a MyClass::create() 

int main()
{
   MyClass* p = MyClass::create();
   ...
   delete p;
   ...
} 


If you want allocate a memory only in stack :
class MyClass {
public:
    // The create() methods are the "named constructors":
   static void create() 
   { 
     MyClass myObj(); 
     .....
   } // here the myObj will be killed
    ...
private:
   // The constructors themselves are private or protected:
  MyClass();
   ...
}; 

//Now the only way to create Fred objects - a MyClass::create (): 

int main()
{
  MyClass::create();

} 


Regards,
Alex

P.S. Do not forget to vote if my answer helped you
 
Share this answer
 
Comments
Aescleal 24-May-12 12:32pm    
When MyClass::create() gets called there's no object created so I can't see how that works. I've given you a three so far, if you clear that up I'll bump it up.
Sergey Alexandrovich Kryukov 24-May-12 18:01pm    
Of course. I would say, there is no a useful method of making it "stack-only" except passing some function pointer as a parameter of create to do some processing.
About "heap-only" approach I would note that the pointer itself is another object which could be placed on stack anyway, and this cannot be prevented.
Voted 4 (would vote 5 if some explanations were added :-).
--SA
Volynsky Alex 25-May-12 11:36am    
Okay, but sourabhmehta asked how to make the creation of a local object.
I hope that you will not mind that this is what makes the second version of my function...
However, there is another way to do it...
The way may be useful to prohibit creation of objects on the heap. C++ has idiomatic ways to achieve this:
#include <string.h>

class MyClassPreventToUseHeap
{
public:
MyClassPreventToUseHeap() {}
~MyClassPreventToUseHeap() {}

private:
//Notice, this only declaration !!!!
void* operator new(size_t) {}
void* operator new[](size_t) {}
void operator delete(void*) {}
void operator delete[](void*) {}
};


int main()
{
/*error C2248: 'MyClassPreventToUseHeap::operator new' :
cannot access private member declared in class 'MyClassPreventToUseHeap'
error C2248: 'MyClassPreventToUseHeap::operator delete' :
cannot access private member declared in class 'MyClassPreventToUseHeap'*/
MyClassPreventToUseHeap *ptr= new MyClassPreventToUseHeap;

// Created on stack, i.e. auto object
MyClassPreventToUseHeap obj;

//Created on static memory
static MyClassPreventToUseHeap obj1;

return 0;
}

I think it is impossible to prevent users from creating objects with static storage duration, because the only difference is the lifetime. but perhaps some experts here can devise a way.

P.S. About "heap-only" approach....
SAKryukov! You're right, the pointer (MyClass * p) sits on the stack, but as I understand the questioner wondered how to place/locate the object on the stack/heap, not his pointer.
No?
Aescleal 27-May-12 2:43am    
Your comment's incorrect in the private section - the four functions there have been defined (i.e. got a defining declaration in standard speak) as well as declared.
Volynsky Alex 27-May-12 4:50am    
I don't understand you.
I will be grateful to you if you explain what is wrong with my comments?
Why you think...it incorrect...? It will work on any compile...
You could accomplish the first by only using local variables, and no pointers.

The second is to my knowledge impossible, memory on the heap is allocated when new is used, to accomplish anything you'd still need a pointer on the stack to make use of it. Plus calling any function will use the stack to store information like the return address. It just isn't feasible.
 
Share this answer
 
Comments
sourabhmehta 24-May-12 11:23am    
Thanks for replying :)

May be i am not clear with the question. Let me rephrase it.

Here my AIM is to "Restrict Object Allocation to Specific Memory Types (say stack or heap)"
lewax00 24-May-12 11:34am    
My answer doesn't change much, you would have to enforce either the use of only locals (for the stack) or only pointers (for the heap) for objects.

What exactly are you trying to accomplish by doing this? If you can tell me, I might be able to get a better idea of what to do.
Aescleal 24-May-12 12:38pm    
I have no idea what he's trying to accomplish, but some C++ programming idioms like having members doing a delete this; as their last operation - modeless dialogues in MFC for example. The problem comes when what if some muppet creates an object on the stack of these types? When they go out of scope they try and delete themselves and all sort of interesting things can happen.

As for why you'd want stack based objects only I can only just think of is stopping idiot ex-Java programmers using new everywhere, but maybe that's just people I work with. :-)
lewax00 24-May-12 13:18pm    
I wasn't aware of that, that's interesting. I've spent too much time recently mucking around with OS design and compilers to think that there might be a higher-level construct that allowed for that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900