[英]In-class / constructor member initialization
我將嘗試總結我在單詞和代碼片段中所需要的東西。
我有一個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
類是一個龐大的類)。
謝謝你
“但這不是一個選擇,因為在將它傳遞給Bar構造函數之前,我需要對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.