0

I accidentally messed up a c++ member value definition:

struct Composite
{
    std::shared_ptr<MyStruct> member = member = std::make_shared<MyStruct>();
    //                                 ^^^^^^
};

Demo

I only discovered the code after some segmentation fault error in code that was copy-pasting the above; I still don't know if the segfault was due to the above. To my surprise such code compiles, and as shown in the linked demo, it seems to work fine (although I cannot guarantee that). My question is:

  1. Is this valid code?
  2. If not, what is the language specification that bans it?
  3. If yes, how on earth is it legal to refer to yourself during definition? The object doesn't yet exist, so isn't there a recursive definition error involved. Curiously, such code is even possible during non member variable definition like int k = k;, so it's not a weird rule about scope inside a class. Is this some omission in the language specification, or is it intentional?
Lorah Attkins
  • 4,604
  • 3
  • 24
  • 56
  • I consider it a C++ idiosyncrasy. Bjarne Stroustrup told a coworker of mine that `int k = k;` can be a way to express the intent of having k in an uninitialized state. Not a convention that I've seen in the wild, and doesn't "scale" to classes. I've seen example code using `Foo foo(&foo);` versus `Foo const foo2(&foo2);` as a self-referential means to check if Foo is being constructed as mutable or const in its own constructor, for what limited application that would have. – Eljay Apr 20 '22 at 17:13

0 Answers0