How can one create a C++ class whose objects can be put only on the stack, as single instances, but
- not into a
std::vector
(or other std container) and also not in a plain array no matter where these are allocated. - not on the heap (answer linked to)
- not as member into another object, if that object itself lives in a container or in the free store.
Note: How do I prevent a class from being allocated via the 'new' operator? (I'd like to ensure my RAII class is always allocated on the stack.) asks how to avoid the free store, but that's only half the answer. I guess(?) for containers, one can do something similar with the placement-new operator, but what's with arrays and the data-member case?
The restriction should be compiler-enforced. (No runtime checking.)
By example:
class User {
...
StackOnly m; // may be OK (depending if below implementable)
};
void f() {
StackOnly obj; //ok
StackOnly arrobj[42]; // fail!
StackOnly* pObj = new StackOnly(); // fail!
std::vector<StackOnly> v; // fail!
User obj; //ok
User arrobj[42]; // fail!
User* pObj = new StackOnly(); // fail!
std::vector<User> v; // fail!
}