简体   繁体   English

从C ++构造函数调用其他函数

[英]Calling other functions from a C++ constructor

在初始化所有成员变量之后,从构造函数的主体中调用非虚拟函数(包括赋值运算符)是否安全?

Yes, constructor can make call to non-virtual functions. 是的,构造函数可以调用非虚拟函数。

Make sure all members have been initialized properly before calling assignment operator otherwise object will be in an inconsistent state. 在调用赋值运算符之前,请确保所有成员均已正确初始化,否则对象将处于不一致状态。

Use the "Virtual Constructor idiom" when you want to call virtual functions from constructor. 当您要从构造函数调用虚拟函数时,请使用“虚拟构造函数惯用法”。

Yes - you can call other non-virtual member functions freely. 是的-您可以自由调用其他非虚拟成员函数。 You can call virtual functions if the most derived base class provides an implementation you happen to want. 如果最派生的基类提供您恰巧想要的实现,则可以调用虚拟函数。

Indeed, before C++11 let one constructor call another, it wasn't uncommon for several constructors to call a support function to perform shared initialisation. 确实,在C ++ 11让一个构造函数调用另一个构造函数之前,多个构造函数调用支持函数执行共享初始化并不罕见。

operator= can be called in these circumstances - the crucial thing is that any clean-up it might attempt before assigning new state will find sane values to operate on - for example, pointers set to nullptr so delete is safe. 在这种情况下可以调用operator= -至关重要的是,在分配新状态之前它可能尝试进行的任何清理都会找到可操作的合理值-例如,将指针设置为nullptr以便delete是安全的。

Note that any exceptions from other functions you call that are allowed to cause the constructor to exit (ie not caught and suppressed) will prevent the object coming into existence - same as for exceptions thrown directly from the constructor function. 请注意,您调用的其他任何允许导致构造函数退出的异常(即未捕获和抑制)都将阻止对象的存在-与直接从构造函数抛出的异常相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM