Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

c++ - Calling virtual function from destructor

Is this safe ?

class Derived:  public PublicBase, private PrivateBase
{
 ... 

   ~Derived()
   {
      FunctionCall();
   }

   virtual void FunctionCall()
   {
      PrivateBase::FunctionCall();
   }
}

class PublicBase
{
   virtual ~PublicBase(){};
   virtual void FunctionCall() = 0;
}

class PrivateBase
{
   virtual ~PrivateBase(){};
   virtual void FunctionCall()
   {
    ....
   }
}


PublicBase* ptrBase = new Derived();
delete ptrBase;

This code crases sometimes with IP in a bad address.

That is not a good idea to call a virtual function on constructor is clear for everyone.

From articles like http://www.artima.com/cppsource/nevercall.html I understand that destructor is also a not so good place to call a virtual function.

My question is "Is this true ?" I have tested with VS2010 and VS2005 and PrivateBase::FunctionCall is called. Is undefined behavior ?

question from:https://stackoverflow.com/questions/12092933/calling-virtual-function-from-destructor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am going to go against the flow here... but first, I must assume that your PublicBase destructor is virtual, as otherwise the Derived destructor will never be called.

It is usually not a good idea to call a virtual function from a constructor/destructor

The reason for this is that dynamic dispatch is strange during these two operations. The actual type of the object changes during construction and it changes again during destruction. When a destructor is being executed, the object is of exactly that type, and never a type derived from it. Dynamic dispatch is in effect at all time, but the final overrider of the virtual function will change depending where in the hierarchy you are.

That is, you should never expect a call to a virtual function in a constructor/destructor to be executed in any type that derived from the type of the constructor/destructor being executed.

But

In your particular case, the final overrider (at least for this part of the hierarchy) is above your level. Moreover, you are not using dynamic dispatch at all. The call PrivateBase::FunctionCall(); is statically resolved, and effectively equivalent to a call to any non-virtual function. The fact that the function is virtual or not does not affect this call.

So yes it is fine doing as you are doing, although you will be forced to explain this in code reviews as most people learn the mantra of the rule rather than the reason for it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...