Re: check that a member function really operates on an object of the expected type

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Ian Lance Taylor skrev:
> Erik <esigra@xxxxxxxxx> writes:
>   
>> This will throw std::bad_cast if the bug in question is encountered. Of
>> course it is not practically possible to add such an assertion to the
>> beginning of every method, but there should be a compiler flag to enable
>> this (in debug builds). Is there such a flag? Is there a feature request
>> for it?
>>     
>
> even if there were such a flag, it would not work reliably for your example.

It must work reliably for my example (and it does). This is explained in
"The C++ Programming Language" by Bjarne Stroustrup. Quote from chapter
15.4.3 (page 414):
   A class is more than simply a region of memory (§4.9.6). A class
object is built from "raw memory" by its constructors and it reverts to
"raw memory" as its destructors are executed. Construction is bottom up
and destruction is top down, and a class object is an object to the
extent that it has been constructed or destroyed. This reflects the
rules for RTTI, exception handling (§14.4.7), and virtual function.
   It is extremely unwise to rely on details of the order of
construction and destruction, but that order can be observed by calling
virtual functions, dynamic_cast, or typeid (§15.4.4) at a point where
the object isn't complete. For example, if the constructor for Component
in the hierarchy from §15.4.2 calls a virtual function, it will invoke a
version defined for Storable or Component, but not one from Receiver,
Transmitter, or Radio. At that point of construction, the object isn't
yet a Radio; it is merely a partially constructed object. It is best to
avoid calling virtual functions during construction and destruction.


> This is an area better addressed by -fmudflap or valgrind.
>   

Valgrind only keeps track of whether a certain piece of memory is
allocated and initialized. To use Bjarne Stroustrup's words, it works on
the "raw memory" level. It does not understand C++ semantics, object
construction/destruction or dynamic_casts. It will not detect access to
a piece of memory that was part of an object but has reverted to "raw
memory" by a destructor. So it can not detect the bug in question.
(Since the object is not completely destroyed yet, its memory block is
still allocated, so Valgrind will not react on the bug. I do not know
what -fmudflap can do.)

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux