0

When I have a shared_ptr to a derived type, but the type of the shared_ptr is to the base type, I cannot see anything but the base type's members in the Locals window of Visual Studio (as if the object was sliced).

Below is a very small program that shows the issue I'm seeing. If a breakpoint is set after the shared_ptr is constructed, and the variable sp is viewed in the Locals window, dvalue cannot be seen.

Is there a way to see this? Perhaps I've been spoiled by managed code...

#include <memory>

struct Base {
    int ivalue;
};

struct Derived : public Base {
    double dvalue;
};

int main() {
    Derived d;
    d.ivalue = 42;
    d.dvalue = 3.14;
    auto sp = std::make_shared<Base>(d);

    // break here

    return 0;
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Steve
  • 6,334
  • 4
  • 39
  • 67

1 Answers1

0

std:make_shared creates a new object based on the type you provided, so in your code, it creates a 'Base" object and points to it, not point to the instance 'd'.

You can add the copy constructor to the structs, and place break pointer in them, and see which one is called:

struct Base {
    int ivalue;

    Base(const Base& b)
    {
        ivalue  = b.ivalue;

    }
};

struct Derived : public Base {
    double dvalue;

    Derived(const Derived& b)
    {
        ivalue  = b.ivalue;
        dvalue = b.dvalue;

    }
};

As you want to see the values in Derived object, you can get raw address of the 'Base' pointer in shared_ptr, just add this to the watch window:

(Derived*))0x45467890
Matt
  • 6,010
  • 25
  • 36
  • Ah, that makes sense... I failed to consider the variance of the types. Instead of `auto`, I should have used `std::shared_ptr sp = std::make_shared(d);` – Steve Apr 10 '14 at 19:05
  • Although... That makes it very difficult for some things. I have a vector of shared pointers like this, and I would like to browse through them while debugging, but that's not possible (without going through the casting watch rigamarole)? I have about 9 different sub-types in my vector. – Steve Apr 10 '14 at 19:28
  • http://msdn.microsoft.com/en-us/library/y2t7ahxk.aspx, explains the expression which can be used in Watch Window; I don't see there's another way. – Matt Apr 10 '14 at 19:38