我将尝试用文字和代码片段来总结我需要的内容。
我有一个类 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/