【问题标题】:In Visual Studio 2019 C++, how can I expand a dynamically allocated array so that all of its elements are displayed?在 Visual Studio 2019 C++ 中,如何扩展动态分配的数组以显示其所有元素?
【发布时间】:2020-04-09 08:39:46
【问题描述】:

我为向量类编写了一个简单(可能很糟糕)的实现,类似于 std::vector。

这是课程:

template <class T>
class Vector
{
    T* data;
    int size;
public:
    Vector(int = 0);
    ~Vector();

    Vector(const Vector<T>&);
    
    Vector<T>& operator=(Vector<T>);
    T& operator[](int);

    friend void swap(Vector<T>&, Vector<T>&);

    void Clear();
    void Insert(T, int);
    void Delete(int);
    int Size();
};

在调试使用我的向量的代码时,我注意到我在内部使用的指针通常只能扩展到第一个元素。

我发现了这个 SO 问题,How to display a dynamically allocated array in the Visual Studio debugger?,它似乎为问题提供了一个简单的解决方案,但我想知道是否可以将数组扩展一个非常量(例如,当前向量大小) .

考虑到 std::vector 确实在调试器中正常显示其所有元素,我是否可以重写我的向量以包含该功能?

这是带有一些测试变量的“Locals”选项卡的片段,以显示我所指的内容:

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读the help pages,接受SO tour,阅读How to Ask,以及this question checklist。最后请学习如何创建一个minimal reproducible example 和edit 你的问题来展示它。
  • @Someprogrammerdude 我认为这不适用于这里。问题不在于调试代码。这是关于在调试器中自定义漂亮的打印,我认为问题已经足够清楚地说明了。
  • 我想知道这是否可以通过 Client Block Hook Function 向 VC 调试器报告信息来完成 - 但我看到的所有示例都只是将信息写入标准输出 - 我想你可能不得不使用 COM (EnvDTE 等)在您的 _CrtSetDumpClient 回调中 - 但这会增加代码的复杂性。
  • FWIW 我找不到任何有关用于指定调试器行为的自定义 __declspec 属性的任何信息(与 .NET Framework 的 [DebuggerDisplayAttribute] 不同)。这是一种耻辱——而且相当令人惊讶。 (公平地说,您可以在 C++ 代码中使用 DebuggerDisplay,但只能使用 C++/CLI - 这不是“真正的”C++...)

标签: c++ debugging visual-studio-2019 stdvector debuggervisualizer


【解决方案1】:

我似乎找到了使用 .natvis 文件的方法。

本文提供了有关 Natvis 文件的更多详细信息: https://docs.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects?view=vs-2019

向您的项目添加 .natvis 文件允许您指定容器在 Locals 中的显示方式。

这是原帖中描述的 Vector 容器的简单示例:

<?xml version="1.0" encoding="utf-8"?> 
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="AC::Vector&lt;*&gt;">
    <DisplayString>{{ size={size} }}</DisplayString>
    <Expand>
      <Item Name="[size]" ExcludeView="simple">size</Item>
      <ArrayItems>
        <Size>size</Size>
        <ValuePointer>data</ValuePointer>
      </ArrayItems>
    </Expand>
  </Type>

</AutoVisualizer>

创建文件并启动调试会话后,容器现在可以正确显示其内容:

AC::Vector<int> myVec(3);
myVec[0] = 1;
myVec[1] = 2;
myVec[2] = 3;

当地人:

【讨论】:

    猜你喜欢
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多