在-class/构造函数成员初始化

In-class / constructor member initialization

我会尝试用文字和代码片段来总结我需要的内容。

我有一个 class、Foo,其中包含类型为 Bar:

的数据成员
class Foo {
  public:

    Bar instance_of_Bar;

    Foo (int some_data) 
    {
      // I need to initialize instance_of_Bar using one of its
      // constructors here, but I need to do some processing first


      // This is highly discouraged (and I prefer not to use smart pointers here)
      instance_of_bar = Bar(..);
      // As an unrelated question: will instance_of_Bar be default-initialized 
      // inside the constructor before the above assignment?
    }
}

显然,"correct" 方法是使用这样的初始化列表:

Foo (int some_data) : instance_of_Bar(some_data) {}

但这不是一个选项,因为我需要在 some_data 上做一些工作,然后再将其传递给 Bar 构造函数。

希望我说清楚了。 RAII 以最少的开销和复制来完成它的方式是什么(Bar class 是一个沉重的方法)。

非常感谢。

"But this is not an option because I need to do some work on some_data before passing it to the Bar constructor."

"do some work on some_data"提供另一个功能如何:

 Foo (int some_data) : instance_of_Bar(baz(some_data)) {}

 int baz(int some_data) {
     // do some work
     return some_data;
 }