Can I use C++ class members initialized in the initializer list, later in the list?

前端 未结 2 1003
悲&欢浪女
悲&欢浪女 2021-01-12 13:06

I am rewriting some code to eliminate global variables and made a class constructor/destructor handle cleanup of some third party library resources, but I am concerned about

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-12 13:29

    Kind of. The rules is that the member variables are initialised in the order they are declared in the class declaration.

    In your case, it is fine since device is declared before document.

    However, in the following case, we have undefined behaviour, despite the order of the initialiser list.

    class A {
    public:
      A(int i) : b(i), a(b) { }
    private:
      int a;
      int b;
    }
    

提交回复
热议问题