Is stack-only variable possible in C++?
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 开发者_如何学Cwant 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?
Well, what about you overload operator new
for your class and delcare it private?
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.
}
精彩评论