-->

How to remediate Microsoft typeinfo.name() memory

2019-09-15 16:14发布

问题:

Microsoft has a decades old bug when using its leak check gear in debug builds. The leak is reported from the allocation made by the runtime library when using C++ type information, like typeinfo.name(). Also see Memory leaks reported by debug CRT inside typeinfo.name() on Microsoft Connect.

We've been getting error reports and user list discussions because of the leaks for about the same amount of time. The Microsoft bug could also mask real leaks from user programs. The latter point is especially worrisome to me because we may not tending to real problems because of the masking.

I'd like to try to squash the leaks due to use of typeid(T) and typeinfo.name(). My question is, how can we work around Microsoft's bug? Is there a work around available?

回答1:

On the line of my suggestion in the Q's comments.

For if (valueType == typeid(int)) you can use the type_index (at least since C++11)


For type_info.name() leaking memory:

Since totally eliminating the leak doesn't seem possible, the next best thing would be reduce their number (to only one leaked per type interrogation) and, secondary, to tag them for reporting purposes.
Being inside some templated classes, one can hope that the 'mem leaking' report will use the class names (or at least the source file where the allocation happened) - you can subsequently use this information to filter them out from the 'all leaked memory' reports.

So instead of using typeid(<typename>), you use something like:

"file typeid_name_workaround.hpp"

template <typename T> struct get_type_name {
  static const char* name() const {
    static const char* ret=typeid(T).name();
    return ret;
  }
};

Other .cpp/.hpp file

#include "typeid_name_workaround.hpp"

struct dummy {
};

int main() {
  // instead of typeid(dummy).name() you use
  get_type_name<dummy>::name();
}