0

C++ allows self initialization.

I understand lines like the following result in j's value being unspecified or just in undefined behavior:

int j = j;

However, the following self-initialization is fine:

void* myAddr = &myAddr;

My questions are:

  1. As I can't come up with any, can anybody provide an example where a self initialization like the latter may actually be useful?

  2. Is there any other self initialization that doesn't result in undefined behavior nor in the variable's value being unspecified? I.e. is there any other well-behaved self initialization?

paolo
  • 2,345
  • 1
  • 3
  • 17
  • you are already giving a use case in the second line. Or are you asking for use cases of `int j = j;` specifically? – 463035818_is_not_an_ai May 30 '22 at 09:27
  • I'm pointing out I know the first line is UB and I'd like to know when the second line may be useful. – paolo May 30 '22 at 09:31
  • then I do not understand the quesiton. Why would it be not useful? Its somewhat like asking, "whats a usecase of `int i = 42;` ?" – 463035818_is_not_an_ai May 30 '22 at 09:32
  • I'm not saying it's useless. I just can't think of any use case where it would be useful to initialize a `void*` variable with its address: that's what I'd like to know. Also, I believe you can only do this with a pointer to `void`, as doing it with any other type would result in a compiler error, right? – paolo May 30 '22 at 09:41
  • 2
    A use case may be a circular list of length one. See this answer: https://stackoverflow.com/a/2532108/580083. – Daniel Langr May 30 '22 at 10:14
  • its not only `void*`. It can also be `Foo f{&f};` or even `Foo f{f};` when the constructor takes a reference – 463035818_is_not_an_ai May 30 '22 at 10:52

0 Answers0