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

前端 未结 2 981
悲&欢浪女
悲&欢浪女 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;
    }
    
    0 讨论(0)
  • 2021-01-12 13:31

    The members are initialized in the order they are declared, top to bottom

    PoDoFo::PdfOutputDevice device;
    PoDoFo::PdfStreamedDocument document;
    PoDoFo::PdfPainter painter;
    

    so it is safe to use device to initialize document.

    0 讨论(0)
提交回复
热议问题