【发布时间】:2015-04-18 09:24:20
【问题描述】:
我将尝试用文字和代码 sn-ps 来总结我需要的内容。
我有一个类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) {}
但这不是一个选项,因为在将 some_data 传递给 Bar 构造函数之前,我需要做一些工作。
希望我说清楚了。以最小的开销和复制来做这件事的 RAII 方法是什么(Bar 类是一个很大的类)。
非常感谢。
【问题讨论】:
-
new Bar(..);顺便说一句是错误的。 -
当然,我的意思是一般的动态分配。我修复了代码 sn-p(我知道这是不好的做法,只是想指出一个明显的替代方案)。
-
我不是都没有必要,你可以使用一个临时实例从:
instance_of_bar = Bar(...);复制。 -
再次编辑了我的问题。感谢您的指正。对我来说,编辑我的问题很重要,这样偶然发现它们的人就不会接受糟糕的编码实践。关于这个方法只有一个问题,临时实例是在堆栈上分配并自动销毁还是会泄漏内存?
标签: c++ constructor initialization raii