简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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