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

librik
  • 3,738
  • 1
  • 19
  • 20
anonymous
  • 1,920
  • 2
  • 20
  • 30
  • 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? – anonymous Sep 19 '13 at 07:25
  • 1
    See [this question](http://stackoverflow.com/questions/16360620/find-out-whether-a-pointer-is-pointing-at-the-stack-heap-or-program-text). 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*. – us2012 Sep 19 '13 at 07:29
  • Thanks that was very informative indeed. – anonymous Sep 19 '13 at 07:44

1 Answers1

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.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
  • Thanks but I am using Sun Studio which is not C++ 11 compliant and I dont think it will be in near or far. – anonymous Sep 19 '13 at 08:09
  • @NIRAJRATHI - the Oracle Solaris Studio developers have said C++11 support is under development: https://forums.oracle.com/message/9954921 and the beta docs for the next version show parts are supported: http://docs.oracle.com/cd/E37069_01/html/E37071/gncix.html#scrolltoc – alanc Sep 19 '13 at 14:41