Reputation: 1968
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
Upvotes: 2
Views: 131
Reputation: 299930
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.
Upvotes: 2