簡體   English   中英

在 Visual Studio 2019 C++ 中,如何擴展動態分配的數組以顯示其所有元素?

[英]In Visual Studio 2019 C++, how can I expand a dynamically allocated array so that all of its elements are displayed?

我已經為向量 class 編寫了一個簡單(並且可能很糟糕)的實現,類似於 std::vector。

這是 class:

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 問題, 如何在 Visual Studio 調試器中顯示動態分配的數組? ,這似乎為問題提供了一個簡單的解決方案,但我想知道是否可以將數組擴展一個非常量(例如,當前向量大小)。

考慮到 std::vector 確實在調試器中正常顯示其所有元素,我是否可以重寫我的向量以包含該功能?

這是帶有一些測試變量的“Locals”選項卡的片段,以顯示我所指的內容:

看來我找到了如何使用 .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>

創建文件並開始調試 session 后,容器現在可以正確顯示其內容:

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

當地人:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM