1

[class.static.data]/2:

The declaration of a non-inline static data member in its class definition is not a definition and may be of an incomplete type other than cv void. ...

That means, this is a valid code:

#include <iostream>
struct S
{
   static S s;
};

S S::s;

int main()
{
    std::cout << &(S::s) << '\n';
    std::cout << &(S::S::s) << '\n';
}

The snippet above prints the same address for &(S::s) and &(S::S::s).

What is the reason for allowing such a construction in C++?

drescherjm
  • 10,365
  • 5
  • 44
  • 64
João Afonso
  • 1,934
  • 13
  • 19
  • 2
    Singletons come to mind. The merits of a singleton defined like that are another matter. – StoryTeller - Unslander Monica Dec 24 '17 at 13:18
  • 6
    Because the storage for `static S s;` is not allocated inside an instance of `S` so the sizeof `S` is known at compile time. Remove the `static` and you get error(s). – Richard Critten Dec 24 '17 at 13:30
  • 3
    Im a bit confused. The quote is about definitions of static data members, but the question seems to be about the injected class name. This would work exactly the same with any other thing declared inside `S`. – Quentin Dec 24 '17 at 13:30
  • @RichardCritten That's pretty clear to me. But my question is: what is the purpose of allowing this construction in C++? The compiler could simply emit an error in this case, as it doesn't add anything to the code, as far as I can tell. – João Afonso Dec 24 '17 at 13:41
  • 1
    If I wanted a static S::s, how else would I declare it? – Richard Critten Dec 24 '17 at 13:47
  • Sorry about the accidental edit. I rolled it back. I have to not try to edit before I have my first coffee. I thought I was editing the code that I copied to ideone.. – drescherjm Dec 24 '17 at 13:56
  • 1
    @drescherjm good morning ;) – Quentin Dec 24 '17 at 13:56
  • "That means, this is a valid code:" No, that means `S::s.s` is valid. (`S::S::x` is indeed valid, but that is for another reason.) – cpplearner Dec 24 '17 at 14:58
  • The link in the question seems to be broken – StayOnTarget Jan 02 '18 at 13:48

0 Answers0