简体   繁体   English

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

[英]In-class / constructor member initialization

I'll try to summarize what I need in both words and code snippets. 我将尝试总结我在单词和代码片段中所需要的东西。

I have a class, Foo , which contains a data member of the type Bar : 我有一个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?
    }
}

Obviously, the "correct" way to do it would be to use an initializer list like this: 显然,“正确”的方法是使用如下的初始化列表:

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

But this is not an option because I need to do some work on some_data before passing it to the Bar constructor. 但这不是一个选择,因为在将它传递给Bar构造函数之前,我需要对some_data做一些工作。

Hopefully I made myself clear. 希望我能说清楚。 What would be the RAII way of doing it with minimal overhead and copying (The Bar class is a hefty one). 用最少的开销和复制完成RAII的方式是什么( Bar类是一个庞大的类)。

Thanks a bunch. 谢谢你

"But this is not an option because I need to do some work on some_data before passing it to the Bar constructor." “但这不是一个选择,因为在将它传递给Bar构造函数之前,我需要对some_data做一些工作。”

What about providing another function to "do some work on some_data " : 如何提供另一个功能“对some_data做一些工作”

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM