延迟初始化私有类成员的最佳实践 [英] Best practice for deferred initialization of private class members

查看:64
本文介绍了延迟初始化私有类成员的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在延迟初始化类 C 的私有类成员 M 的最佳实践?例如:

Is there a best practice for deferred initialization of a private class member M of class C? For example:

class C {
public:
    C();

    // This works properly without m, and maybe called at any time,
    // even before startWork was called.
    someSimpleStuff();

    // Called single time, once param is known and work can be started.
    startWork(int param); 

    // Uses m. Called multiple times.
    // Guaranteed to only be called after startWork was called 
    doProcessing(); 

private:
    M m;
};

class M {
    M(int param);
};

C 类的对象不能是构造是因为 M 没有默认的初始化程序。

Objects of class C can't be constructed because M doesn't have a default initializer.

如果可以修改 M 的实现,可以在 M 中添加 init 方法,并使其构造函数不接受任何参数,这将允许构造类 C 的对象。

If you can modify M's implementation, it's possible to add an init method to M, and make its constructor accept no arguments, which would allow constructing objects of class C.

如果没有,则可以包装 C 的成员 std :: unique_ptr 中的成员 m ,以及

If not, you can wrap the C's member m in std::unique_ptr, and construct it when it becomes possible.

但是,这两种解决方案都容易出错,并且会在运行时捕获。是否有一些实践可确保在编译时确保 m 仅在初始化后才使用?

However, both these solutions are prone to errors which would be caught in run-time. Is there some practice to make sure at compile-time that m is only used after its been initialized?

限制:类C的对象被传递到使用其公共接口的外部代码,因此C的公共方法不能拆分为多个类。

Restriction: An object of class C is handed to external code which makes use of its public interface, so C's public methods can't be split into multiple classes.

推荐答案

最佳实践是从不使用延迟初始化。

The best practice is to never used deferred initialisation.

在您的情况下,请放弃默认的构造函数,以 C 并替换为 C(int param):m(param){} 。也就是说,使用基础成员初始化在类构建时对类成员进行初始化。

In your case, ditch the default constructor for C and replace it with C(int param) : m(param){}. That is, class members get initialised at the point of construction using base member initialisation.

使用延迟初始化意味着您的对象可能处于不确定状态,并实现并发性更难。

Using deferred initialisation means your object is potentially in an undefined state, and achieving things like concurrency is harder.

这篇关于延迟初始化私有类成员的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆