0

I've come across some code looking like the following -

class A
{
     public:
          A();
          ~A();
}a;

This occurs in in foo.cpp, and there is a foo.hpp where class A sees no use at all. This is the only usage of this class in an entire code base. The instance a sees no use anywhere inside foo.cpp.

When is a created and destroyed?

Since it's been marked as a duplicate I'll highlight/extend the bit that makes it not a duplicate -

Does this style of instantiating a class alongside its definition have a name?

There is a comment alongside this class that describes it as a singleton. Is that correct? I realize it doesn't follow the GoF implementation of a singleton, but this is only instance of A that can exist correct (given that it's not used anywhere else inside of foo.cpp)?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
LBaelish
  • 649
  • 1
  • 8
  • 21
  • Global variables have a lifetime of the whole programs execution. They should be constructed before the `main` function starts, and be destructed after `main` returns (or `exit` is called). – Some programmer dude Dec 10 '17 at 00:45
  • And no, it's *not* a singleton in the classic sense. Actually, it should not be possible to create even the `a` object since both the constuctor and destructor are `private`. If what you show is not an actual [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve), and the constructor and destructor is actually `public`, then it's *still* not a singleton, since other objects could then be created (even if none are *currently*). – Some programmer dude Dec 10 '17 at 00:46
  • @Someprogrammerdude That was an omission on my part and has been corrected. – LBaelish Dec 10 '17 at 00:48
  • It is important to note that this is equivalent to defining class A and then immediately declaring `A a;`. Therefore, this is only a global variable if this code is in the global scope. Otherwise it is just a locally defined class and `a` is a local variable. – patatahooligan Dec 10 '17 at 00:52

0 Answers0