且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 DDD(或 gdb)中使用 unique_ptr 调试 C++11 代码?

更新时间:2022-05-18 23:20:41

这个问题其实和C++11、unique_ptr或者漂亮的打印无关.问题是 gcc 不会为 std::unique_ptr::operator* 发出代码,gdb 可以调用这些代码来取消对 unique_ptr 的引用.例如,如果您将 *pTest; 添加到您的代码中,则 gdb 会执行取消引用.

This problem is actually not related to C++11, unique_ptr or pretty printing. The problem is that gcc does not emit code for std::unique_ptr::operator* that could be called by gdb to dereference the unique_ptr. If you for instance add *pTest; to your code then gdb does perform the dereferencing.

SO 帖子中描述了类似的问题 How to`print`/评估 gdb 中的 c++ 模板函数.https://sourceware.org/ml 中的 auto_ptr 描述了几乎相同的问题/archer/2012-q1/msg00003.html.如果我正确理解线程,一种解决方法是修补漂亮的打印机,并在打印 unique_ptr 时打印出取消引用的指针.可以在 http://sourceware.org/bugzilla/show_bug.cgi 找到 gdb 错误报告?id=12937.

A similar problem is described in the SO post How to `print`/evaluate c++ template functions in gdb. Almost the same problem is described for an auto_ptr at https://sourceware.org/ml/archer/2012-q1/msg00003.html. If I understand the thread correctly one workaround would be to patch the pretty printer and also print out the dereferenced pointer when printing the unique_ptr. A gdb bug report can be found at http://sourceware.org/bugzilla/show_bug.cgi?id=12937.

https://sourceware.org/gdb/wiki/STLSupport 上的 gdb wiki 描述更漂亮的打印解决方案,可能还有其他解决方法.

The gdb wiki at https://sourceware.org/gdb/wiki/STLSupport describes more pretty printing solutions, which could have other workarounds.

强制编译器为包括 operator* 在内的所有成员模板发出代码的更优雅的解决方案是显式实例化类:

A more elegant solution forcing the compiler to emit code for all member templates including operator* is to explicitly instantiate the class:

template class std::unique_ptr<MyType>;