Search code examples
c++initializer

TCPL 5.9.9 (C++): Where would it make sense to use a name in its own initializer?


This is a question from the most recent version of Stroustrup's "The C++ Programming Language".

I've been mulling this over in my head for the past couple days.

The only thing I can come up with, (and this is probably incorrect) is something like this:

int* f(int n) {
  int* a = &a - n * sizeof(int*);
  return a;
}

My intent is to get the address of something higher up on the stack. Does this make any sense? Does anyone else have any other answers? Remember, this is in Chapter 5 (pointers, arrays, and structures) so the answer shouldn't involve something later on in the book.


Solution

  • The only (barely) reasonable case I know of is when you want to pass a pointer to the object itself to its constructor. For example, say you have a cyclic linked list node:

    class Node
    {
    public:
        Node(Node* next): next(next) {}
    private:
        Node* next;
    };
    

    and you want to create a single-element cyclic list on the stack. You can do this:

    Node n(&n);
    

    A few other examples that aren't really practical (i.e. I don't see why you'd need that sort of thing), but otherwise valid:

    int n = sizeof(n);
    void* p = &p;