c++ - 类内/构造函数成员初始化

标签 c++ constructor initialization raii

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

我有一个类 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?
    }
}

显然,“正确”的方法是使用这样的初始化列表:

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

但这不是一个选项,因为在将它传递给 Bar 构造函数之前,我需要对 some_data 做一些工作。

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

非常感谢。

最佳答案

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

如何提供另一个函数来“对some_data 做一些工作”:

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

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

关于c++ - 类内/构造函数成员初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29715364/

相关文章:

c++ - 在运行时使用不同的构造函数

c++ - 为什么不能简单初始化(带大括号)2D std::array?

c++ - CRTP和模板模板?

Java newColor 构造函数随机化

当涉及 std::function 或 lambda 函数时,C++11 不推导类型

c++ - 使用聚合初始化列表优于构造函数的优势?

objective-c - Objective-C 中的异步初始化

c++ - 初始化全局变量的问题

c# - C#和C++ dll-编码字符串

C++:在堆上分配的对象