1

I have class B, which contains a pointer for object of class A. I want them to share their position, so I used std::shared_ptr for it. Below is a short version of this code:

struct A {
    std::shared_ptr<int> pos;

    A(const A& right, std::shared_ptr<int> _pos = nullptr) :
        pos(_pos == nullptr ? (std::make_shared<int>()) : _pos) { }
};

struct B {
    std::shared_ptr<int> pos;
    A* a;
    
    B(const B& right) :
        pos(std::make_shared<int>()), 
        a(new A(*right.a, pos)) { }
};

In the actual program it seems to work fine, however Visual Studio gives warning C26815 for dangling pointer in the B copy constructor, when giving value to a. Removing pos from B doesn't affect the warning, but if it's also removed from A the warning disappears, so I guess it have something to do with shared_ptr? Is there a dangling pointer here, or it's a false warning?

JHBonarius
  • 10,824
  • 3
  • 22
  • 41
Kitsune
  • 11
  • 2
  • 1
    The problem is likely not with the `std::shared_ptr`, but with `a`, the normal pointer. You are not following the [Rule of Five](https://stackoverflow.com/a/4172724). (And thus have a memory leak when an object of B is destroyed, moved or copied) – JHBonarius Jan 10 '21 at 19:46
  • Unrelated, if you use `std::make_shared()` as the default value of the `_pos` parameter to `A::A` you can eliminate the terse ternary expression in its member-init list. Not sure why you settled on `nullptr`, but it isn't necessary. Just saying. – WhozCraig Jan 10 '21 at 19:48
  • The full error message from that [warning](https://learn.microsoft.com/en-us/cpp/code-quality/c26815?view=msvc-160) is "Warning C26815 The pointer is dangling because it points at a temporary instance that was destroyed." – 1201ProgramAlarm Jan 10 '21 at 19:58
  • 1
    Please give a [mcve]. – JHBonarius Jan 10 '21 at 20:06

0 Answers0