C++ Compiler allows circular definition?

后端 未结 2 729
青春惊慌失措
青春惊慌失措 2021-02-18 14:13

I ran into the following oddity when making a mistake writing some code for trees. I\'ve stripped down this example a lot so it is only a Linear Tree.

Basically, in the

2条回答
  •  無奈伤痛
    2021-02-18 15:06

    Since "root" on the RHS is a flat-out undeclared variable.

    It's not undeclared. It is declared by that very same statement. However, root is uninitialised at the point where AddLeaf(root) is called, so when the value of the object is used (compared to null etc.) within the function, the behaviour is undefined.

    Yes, using a variable in its own declaration is allowed, but using its value is not. Pretty much all you can do with it is take the address or create a reference, or expressions that only deal with type of the sub expression such as sizeof and alignof.

    Yes, there are use cases although they may be rare. For example, you might want to represent a graph, and you might have a constructor for node that takes a pointer to linked node as an argument and you might want to be able to represent a node that links with itself. Thus you might write Node n(&n). I won't argue whether that would be a good design for a graph API.

提交回复
热议问题