C++ CRTP initialization

前端 未结 3 1016
有刺的猬
有刺的猬 2020-12-22 02:05

i ran into a segfault running the following program

#include 
#include 

template 
struct CRTPBase {
           


        
3条回答
  •  情话喂你
    2020-12-22 02:14

    When CRTPBase constructor is called, CRTPChild is not yet fully constructed, so calling it's member function is undefined behavior.

    The way undefined behavior manifests itself depends on platform, compiler and phase of the moon.

    In particular, when your member is an int, the fact that it is not yet constructed doesn't cause program to crash when you are using int - there are no invariants for int. Vector, on the other hand, has invariants, so accessing unconstructed vector will violate them, and cause incorrect memory access.

提交回复
热议问题