Reputation: 1397
I have a class from an external library. Only one instance may exist in the same scope. I can assert(instance_counter<=1)
that no problem in a wrapper class.
But I want to be sure at compile time. Is there any way to do this? I think not, but maybe in c++23 or c++26?
UPDATE The code is such, that nobody would instantiate such a class in a nested scope introduced by a function call even though it would be possible in theory. Hence, nested scope is not a problem that a potential solution needs to tackle.
UPDATE2 A singleton would not work. I really need a constructor and destructor to be invoked to achieve some RAII operations.
Upvotes: 1
Views: 125
Reputation: 217
I don't think there is or will be anything in the standard (as of c++26) allowing you to do that at compile time. Few options remain:
The former is trivial and efficient; the second depends on what you may use, and the latter is many orders of magnitude more difficult...
EDIT: What you are wanting to do is very similar to what clang/rtsan (recent in clang20) do, except they do it to enforce realtime/non-blocking call contexts. Indeed there are static checks (via clang/llvm annotations) which are complemented by a rt checks (librtsan, based on tls counters and RAII scope objects).
Upvotes: 0