C++ 中的两阶段构造

Two phase Construction in C++(C++ 中的两阶段构造)
本文介绍了C++ 中的两阶段构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为任务的一部分,我有研究使用 C++ 类的两阶段"构造的开发工具包:

I have as part of assignment to look into a development kit that uses the "two-phase" construction for C++ classes:

// Include Header
class someFubar{
public:
    someFubar();
    bool Construction(void);
    ~someFubar();
private:
    fooObject _fooObj;
}

在源码中

// someFubar.cpp
someFubar::someFubar : _fooObj(null){ }

bool 
someFubar::Construction(void){
    bool rv = false;
    this->_fooObj = new fooObject();
    if (this->_fooObj != null) rv = true;
    return rv;
}

someFubar::~someFubar(){
    if (this->_fooObj != null) delete this->_fooObj;
}

为什么要使用这种两阶段",有什么好处?为什么不在实际的构造函数中实例化对象初始化?

Why would this "two-phase" be used and what benefits are there? Why not just instantiate the object initialization within the actual constructor?

推荐答案

关于两期建设.

这个想法是你不能从构造函数返回一个值来指示失败.指示构造函数失败的唯一方法是抛出异常.这并不总是可取的,尤其是因为异常安全是一个非常复杂的主题.

The idea is that you cannot return a value from a constructor to indicate failure. The only way to indicate constructor failure is to throw an exception. This is not always desirable, not least because exception safety is a very complex topic.

因此,在这种情况下,构造被拆分:一个不抛出但也不完全初始化的构造函数,以及一个执行初始化并可以返回成功或失败指示而不会(必然)抛出异常的函数.

So in this case the construction is split up: a constructor that does not throw, but also does not fully initialize, and a function that does the initialization and can return an indication of success or failure without (necessarily) throwing exceptions.

这篇关于C++ 中的两阶段构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)