为什么使用初始化方法而不是构造函数? [英] Why use an initialization method instead of a constructor?

查看:207
本文介绍了为什么使用初始化方法而不是构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  struct MyFancyClass:这是一个新的公司, theUberClass 
{
MyFancyClass();
〜MyFancyClass();
resultType initMyFancyClass(fancyArgument arg1,classyArgument arg2,
redundantArgument arg3 = TODO);
//几种奇怪的方法...
};

他们告诉我这和时间有关。有些事情必须在之后执行,否则会在构造函数中失败。但是大多数构造函数都是空的,我真的看不到没有使用构造函数的原因。



因此,我转向你,哦C向导:一个init方法而不是一个构造函数?

解决方案因为他们说timing,我想这是因为他们想要他们的init函数以便能够调用对象上的虚函数。这并不总是在构造函数中工作,因为在基类的构造函数中,对象的派生类部分还不存在,特别是不能访问派生类中定义的虚函数。相反,如果定义,则调用函数的基类版本。如果没有定义,(意味着函数是纯虚拟的),你会得到未定义的行为。



init函数的另一个常见原因是希望避免异常,这是一个漂亮的老式编程风格(和这是一个好主意是一个整体的论点)。它与无法在构造函数中工作的事情无关,而与构造函数无法返回错误值的事实无关。所以,在你的同事给你真正的原因,我怀疑这不是它。


I just got into a new company and much of the code base uses initialization methods instead of constructors.

struct MyFancyClass : theUberClass
{
    MyFancyClass();
    ~MyFancyClass();
    resultType initMyFancyClass(fancyArgument arg1, classyArgument arg2, 
                                redundantArgument arg3=TODO);
    // several fancy methods...
};

They told me that this had something to do with timing. That some things have to be done after construction that would fail in the constructor. But most constructors are empty and I don't really see any reason for not using constructors.

So I turn to you, oh wizards of the C++: why would you use an init-method instead of a constructor?

解决方案

Since they say "timing", I guess it's because they want their init functions to be able to call virtual functions on the object. This doesn't always work in a constructor, because in the constructor of the base class, the derived class part of the object "doesn't exist yet", and in particular you can't access virtual functions defined in the derived class. Instead, the base class version of the function is called, if defined. If it's not defined, (implying that the function is pure virtual), you get undefined behavior.

The other common reason for init functions is a desire to avoid exceptions, but that's a pretty old-school programming style (and whether it's a good idea is a whole argument of its own). It has nothing to do with things that can't work in a constructor, rather to do with the fact that constructors can't return an error value if something fails. So to the extent that your colleagues have given you the real reasons, I suspect this isn't it.

这篇关于为什么使用初始化方法而不是构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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