Patrick Fromberg
Patrick Fromberg

Reputation: 1397

Compile time check that only one instance of a class is instantiated in the same scope

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

Answers (1)

Steve
Steve

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:

  • asserting on a global or tls counter, (at runtime, of course)
  • using an external tool
  • instrumenting the compiler and the linker

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

Related Questions