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

允我心安 提交于 2019-12-04 03:24:38

问题


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 some code which initializes one member from another member in the class initializer list.

class MyPodofoDocument {
public:
    // generates pdf to stream
    MyPodofoDocument(std::stringstream *pStringStream)
        : device(pStringStream), document(&device)
    {
    }
private:
    PoDoFo::PdfOutputDevice device;
    PoDoFo::PdfStreamedDocument document;
    PoDoFo::PdfPainter painter;
};

The code which uses this class doesn't need to see all the details that go into using the library, but the way I hide them makes it dependent on using members to initialize other members, before it hits the constructor's actual code block, where it has a valid this pointer.

It works in a unit test skeleton, so my question is basically, "Is this okay, portable and safe?"


回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/14966501/can-i-use-c-class-members-initialized-in-the-initializer-list-later-in-the-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!