2

I have some unusual requirement that a variable should always be there on heap and not on stack. Now I tried doing this using private destructor and static method of class which will simply take pointer and call delete on it.

Class A { public : static void method(const A* ptr) { delete ptr; } private : ~A(); }; 

But now I am just curious to see better altrnative and one thing came to my mind is if I can add some pre-check to each method to see wheather variable is on stack or on heap then I do not have to declare static method. Can anyone tell me how to do that? I just got one solution on my mind is to use sbrk(0) or pthread API to get boundary of current stack and then compare it with address of class variable but not portable.

Thanks Niraj Rathi

3
  • Test program i posted is in C++ but this is applicable to C as well where in one don't have the ability to detect location of pointer on stack or on heap? Commented Sep 19, 2013 at 7:25
  • 1
    See this question. It's impossible to do this in a portable way. For many system, your current solution will do what you want, although technically it only means that you can't have an A object with automatic storage duration. Commented Sep 19, 2013 at 7:29
  • Thanks that was very informative indeed. Commented Sep 19, 2013 at 7:44

1 Answer 1

2

Actually, your solution does not work.

using Buffer = std::aligned_storage<sizeof(A), alignof(A)>::type; int main() { // Allocate scratch area to build a 'A' Buffer buffer; // Build a 'A' using placement new new (&buffer) A(); // Ensure proper deletion at end of scope using `unique_ptr` // and a custom deleter (and cast to `A*` as we go). std::unique_ptr<A, A::method> a(reinterpret_cast<A*>(&buffer)); a->method(0); // ... } 

So, on top of preventing arbitrary destruction, you also need to prevent arbitrary construction (which includes copy-construction and move-construction). You can leave assignment public because it assigns to an existing object, and by controlling construction you ensured that all existing objects are placed where you wish them to.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but I am using Sun Studio which is not C++ 11 compliant and I dont think it will be in near or far.
@NIRAJRATHI - the Oracle Solaris Studio developers have said C++11 support is under development: forums.oracle.com/message/9954921 and the beta docs for the next version show parts are supported: docs.oracle.com/cd/E37069_01/html/E37071/gncix.html#scrolltoc

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.