Virtual Designer Idiom - Virtuous or Full Mistake

One of the golden rules in C ++ is that the lifetime of an instance begins when its constructor completes successfully and ends when its destructor begins.

From this rule, we conclude that it is not recommended to call virtual methods in the constructor, since a possible derived instance is invalid, which will lead to undefined behavior.

The virtual constructor idiom mentioned in the C ++ FAQ 20.8 points to the opposite.

My question is:

  • What is the exact definition in the standard for determining the lifetime of objects relative to calls from their constructors and destructors?
  • and besides, is this the so-called Idom virtual constructor?
+3
source share
2 answers

I think you are mixing two separate (if vaguely related) things.

  • It is well known that you cannot call virtual functions from constructors (directly or indirectly) for the reasons discussed here .
  • What the FAQ says is calling the constructor from a virtual function. In a sense, this is the opposite of # 1. The idea is to select a constructor (i.e. Class) based on the dynamic type of any existing object.
+7
source

, , , ( , ). , Derived, Base, Base in Base; this Base::Base() Base *, , this. . , .

. , § 12.7 2-3 ++ 03.

.

+2

Source: https://habr.com/ru/post/1779719/


All Articles