Virtual destructor and undefined behavior

前端 未结 4 1389
清歌不尽
清歌不尽 2020-11-28 13:27

This question is different than \'When/why should I use a virtual destructor?\'.

struct B {
  virtual void foo ();
  ~B() {}  // <--         


        
4条回答
  •  感情败类
    2020-11-28 14:13

    As reaffirmed by others this is totally undefined because the Base's destructor is not virtual, and no statements can be made by anybody. See this thread for a reference to the standard and further discussion.

    (Of course, individual compilers are entitled to make certain promises, but I haven't heard anything about that in this case.)

    I find it interesting though, that in this case I think that malloc and free are better defined in some cases than new and delete. Perhaps we should be using those instead :-)

    Given a base class and a derived class, neither of which have any virtual methods, the following is defined:

    Base * ptr = (Base*) malloc(sizeof(Derived)); // No virtual methods anywhere
    free(ptr); // well-defined
    

    You might get a memory leak if D had complex extra members, but apart from this is is defined behaviour.

提交回复
热议问题