I have a C++ class for which I only ever want it to be instantiated on the stack. I am using an api to access content that was developed in another (interpreted) language which comes with its own garbage collection. The mechanisms in this language know enough to leave any content that it finds references to on the stack alone, and since this native class contains such a reference, it is of vital importance that for correct behavior, the user of the native C++ class it does not ever try to allocate an instance of it anywhere else.
Note, I not only want to prohibit the instance of my class from being allocated with new (if that were all I needed to do, I could overload the class's new
operator and make it private, or explicitly delete it since C++11), but to also disallow any static or possible global instances of the class as well. The only valid way to instantiate this class safely should be on the stack, and I would like to somehow guarantee that. As far as I know, making new
private or deleting it also does not prevent another class from being declared with my class as a member variable and an instance of that being allocated on the heap.
How I am managing this right now is to have the word "Local" as part of the name of the class as a friendly reminder to the user that the instance is only intended to be used on the stack, but of course, this isn't actually enforced by the compiler or any other mechanism, and I would prefer a solution that is more enforceable.
Ideally I want to ensure this at compile time and fail compilation if used incorrectly. If this is simply not possible, throwing an exception at runtime when the instance is constructed is still an acceptable fallback. Solutions that work in C++11 or C++14 are fine.
Please note that this question is definitely NOT the same as this one, which only wanted to prevent allocaton with new