C++ Compiler allows circular definition?

后端 未结 2 847
青春惊慌失措
青春惊慌失措 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条回答
  •  萌比男神i
    2021-02-18 14:58

    That's an unfortunate side-effect of definitions in C++, that declaration and definition is done as separate steps. Because the variables are declared first, they can be used in their own initialization:

    std::shared_ptr root = tree.AddLeaf(12, root);
    ^^^^^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^^^^
    Declaration of the variable  Initialization clause of variable
    

    Once the variable is declared, it can be used in the initialization for the full definition of itself.

    It will lead to undefined behavior in AddLeaf if the data of the second argument is used, as the variable is not initialized.

提交回复
热议问题