我可以使用在初始值设定项列表中初始化的C ++类成员吗? [英] Can I use C++ class members initialized in the initializer list, later in the list?

查看:108
本文介绍了我可以使用在初始值设定项列表中初始化的C ++类成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重写一些代码以消除全局变量,并让类构造函数/析构函数处理某些第三方库资源的清除,但是我担心某些代码会从类初始化器列表中的另一个成员初始化一个成员.

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

使用此类的代码不需要查看使用该库所涉及的所有细节,但是我隐藏它们的方式使其依赖于使用成员初始化其他成员,然后才到达构造函数的实际代码块,它具有有效的this指针.

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?"

推荐答案

成员是按照声明的顺序从上到下初始化的

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

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

因此可以安全地使用device初始化document.

so it is safe to use device to initialize document.

这篇关于我可以使用在初始值设定项列表中初始化的C ++类成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆