Are there any specific reasons to use non-virtual destructors?

前端 未结 5 1881
不思量自难忘°
不思量自难忘° 2020-12-30 01:13

As I know, any class that is designated to have subclasses should be declared with virtual destructor, so class instances can be destroyed properly when accessing them throu

5条回答
  •  滥情空心
    2020-12-30 01:48

    Another reason I haven't seen mentioned here are DLL boundaries: You want to use the same allocator to free the object that you used to allocate it.

    If the methods live in a DLL, but the client code instantiates the object with a direct new, then the client's allocator is used to obtain the memory for the object, but the object is filled in with the vtable from the DLL, which points to a destructor that uses the allocator the DLL is linked against to free the object.

    When subclassing classes from the DLL in the client, the problem goes away as the virtual destructor from the DLL is not used.

提交回复
热议问题