tags:

views:

171

answers:

2

Currently I want to make wrapper accessor class in multithreaded environment. The purpose of the class is simple - Grab a lock on its construction and release a lock on its destruction. Other than that, it's identical to a normal pointer. Moreover, I want to prevent it from being created on heap area to ensure that the lock will be released eventually.

The inverse is fairly easy (private constructor with factory method), but I don't know that a stack-only variable is possible. Is there anyway?

+12  A: 

Well, what about you overload operator new for your class and delcare it private?

Armen Tsirunyan
Thanks. I've been completely forgotten about operator new until now! Though it can not completely prevent it from being creating on heap area(since it can be a member variable in an object created by new operator), but it would be helpful to prevent many mistake.
summerlight
@summerlight: I believe it is impossible to COMPLETELY prevent it from being created on the heap compile-time or portably.
Armen Tsirunyan
yup, even with a private `operator new`, it'd be something like 5 lines of code to write a wrapper object which *contains* your object, and which can be allocated on the heap. As always when writing C++ library code, you can't dictate how the user *must* use it. You have to assume that the library user is sane and will not actually try to break his own program. And if you make that assumption, then you don't *need* to make it impossible to heap-allocate your object.
jalf
This doesn't work in the general case, but maybe for this particular use it is okay. There are uses for a new operator that has been defined on the stack. Placement new in particular will still work.
edA-qa mort-ora-y
A: 

I don't understand the problem? Any variable defined within the scope of a function is stack-only.

class Lock {
public:
    Lock() {
        performLock();
    }

    ~Lock() {
        performUnlock();
    }
}

void foo() {
    // ... Code
    Lock onStackOnly;
    // ... Code that is locked
}


void foo() {
    // ... Code
    {
        Lock onStackOnly;
        // ... Code that is locked
    }

    // This code is unlocked.
}
EboMike
"I want to prevent it from being created on heap area". He wants `new Lock();` to not be possible
Michael Mrozek
his question is about how to force the variable to be defined within the scope of a block and to prevent any instantiation on the heap.
BatchyX