-2

I would like to have a variable of the same type as the class it is in. I don't want to use a pointer. I want it to be static AND a const. I have not found a way to do this. I also want an identifier for it.

When I used a pointer, I got a supposed "memory leak".

What I want:

class A {
     std::string str;

     A(std::string str) : str(str)
     {}

    static const A b("hi");
}
  • You either need to separate the declaration and definition or mark the definition [inline](https://stackoverflow.com/questions/38043442/how-do-inline-variables-work) – Nathan Pierson Jul 24 '21 at 18:23
  • Actually I'm not sure you can do `inline static const` right there in the class definition because `A` is an incomplete type at that point. But you can still [do this](https://godbolt.org/z/3Eqdf56jq) to have a separate definition – Nathan Pierson Jul 24 '21 at 18:34
  • are you trying to reinvent a singleton? – Swift - Friday Pie Jul 24 '21 at 20:02
  • Now I get, inline specifier only allowed on functions – SomeRandomCoder Jul 24 '21 at 20:49
  • The inline specifier isn't only allowed on functions, as of C++17. But if we wanted to make it `inline` `A` has to be a complete type, which it isn't while we're still in the body of the definition of `A`. So it may not be possible to do it directly this way. – Nathan Pierson Jul 24 '21 at 21:18

1 Answers1

1

How about

class A {
     std::string str;

     A(std::string str) : str(str)
     {}

    static const A& getA() {
        static const A b("hi");
        return b;
    }
}

That might be a solution, depending on your needs.

Matthias Grün
  • 1,466
  • 1
  • 7
  • 12