Calling a Method in Constructor

前端 未结 5 1862
情书的邮戳
情书的邮戳 2020-12-28 15:49

Herb Sutter mentions in one of his http://www.gotw.ca articles that an object is constructed(has valid existence) only if the constructor executes completes.ie to put it in

5条回答
  •  囚心锁ツ
    2020-12-28 16:07

    Note: it would have been easier with the exact article, so that we could have some context

    Lifetime considerations are actually pretty complicated.

    Considering the constructor of an object, there are two different point of views:

    • external: ie the user of an object
    • internal: ie, you when writing constructors and destructors (notably)

    From the external point of view, the lifetime of an object:

    • begins once the constructor successfully completed
    • ends when the destructor begins to run

    It means that if you attempt to access an object mid-construction or mid-destruction Bad Things Happen (tm). This is mostly relevant to multi-threaded programs, but may happen if you pass pointers to your object to base classes... which leads to...

    ...the internal point of view. It's more complicated. One thing you are sure of is that the required memory has been allocated, however parts of the objects may not be fully initialized yet (after all, you are constructing it).

    • in the body of the constructor, you can use the attributes and bases of the class (they are initialized), and call functions normally (virtual calls should be avoided).
    • if it's a base class, the derived object is not initialized yet (thus the restriction on virtual calls)

提交回复
热议问题