Can we prevent creation of objects with static lifetime, while at the same time allowing objects to be created with automatic lifetime?
If we want to prevent users from creating instances of a class with automatic duration, we can make the destructor private. and if we want to prevent users from creating instances with dynamic allocation, we c开发者_运维百科an make operator new
private.
I think it is impossible to prevent users from creating objects with static storage duration, because the only difference is the lifetime. but perhaps some experts here can devise a way.
There is no language facility which helps at compile time. But at runtime you can use below technique to restrict that. Suppose you don't want MyObject
on static
storage area, then add the code in destructor as:
bool ALLOW_OBJECTS = false; // global variable
struct MyObject // class body
{
~MyObject ()
{
if(ALLOW_OBJECTS == false)
<print error message>
// ...
}
};
Now, in your main()
method you can have ALLOW_OBJECTS
as,
int main ()
{
ALLOW_OBJECTS = true; // objects can be created now
// ... other code
ALLOW_OBJECTS = false; // reset to 'false' before main() ends
}
Now it's a fact that variables declared in static
storage vanish their lifetime (call destructor) after main()
finishes. Thus, if a variable was declared on static
storage, its destructor will print an error message (in file or stdout).
With this check your 1 execution test run may fail, but you can manually correct the code after you find the number of error messages. So in your production code you can remove all those debug statements and you will have your code without any static
storage object !!! (not applicable for PODs and pointers).
There is a receipt on wikibooks Requiring or Prohibiting Heap-based Objects.
The point is to make a class destructor to be protected so the using statically created object will generate a compile-time error. The drawback is that you have to implement and invoke a separate delete method for your class.
class HeapOnly {
public:
HeapOnly() {}
void destroy() const { delete this; }
protected:
~HeapOnly() {}
};
HeapOnly h1; // Destructor is protected so h1 can't be created globally
HeapOnly func() // Compiler error because destructor of temporary is protected
{
HeapOnly *hoptr = new HeapOnly; // This is ok. No destructor is invoked automatically for heap-based objects
return *hoptr;
}
int main(void) {
HeapOnly h2; // Destructor is protected so h2 can't be created on stack
}
精彩评论