简体   繁体   中英

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

I've written a simple (and potentially bad) implementation for a vector class, similar to std::vector.

Here is the 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();
};

When debugging code that uses my vector, I've noticed that the pointer that I'm using internally only expands up to the first element normally.

I found this SO question, How to display a dynamically allocated array in the Visual Studio debugger? , which seems to give a simple solution to the problem, but I'm wondering if it's possible to expand the array by a non-constant amount (say, the current vector size).

Considering that std::vector does show all of its elements normally inside the debugger, could I alternatively rewrite my vector to include that functionality?

Here is a snip of the "Locals" tab with some test variables, to show what I'm referring to:

It seems that I found how to do this using.natvis files.

This article provides more details about Natvis files: https://docs.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects?view=vs-2019

Adding a.natvis file to your project allows you to specify how the container should be displayed in Locals.

Here is a simple example for the Vector container described in the original post:

<?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>

After creating the file and starting the debug session, the container now displays its contents properly:

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

Locals:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM