1

As you might know,

A::A() {
    this->foo = 1;
}

Is the same as:

A::A() : foo(1) {
    this->foo = 1;
}

Which is inefficient because of the double declaration.
The compiler might optimize this, but in my case the class is not a POD.
I must define the member in the constructor body since it can't be compressed into one single line.

Is there any way of doing this?

4

1 回答 1

3

不,您不能在构造函数主体中初始化。它必须在 mem-initialiser 列表中完成,或者使用类内初始化器(在成员声明处)。但是,没有什么可以阻止您调用函数(或 lambda)来进行初始化:

A::A() : foo([]() { /* ... */ } ())
{}

// or

A::A() : foo(initFoo())
{}

Foo A::initFoo() { /* ... */ }
于 2018-02-01T17:20:23.290 回答