Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to member variable of shared_ptr

What is a safe way to accessing member variables through a shared object in C++?

In the code below, I make a shared variable and then a pointer to a member variable of it. However, the use_count remains unchanged and when I reset the shared variable the original variable is reset but not the pointer to member.

In other words, I could introduce some bugs by using b. The object it is pointing to shouldn't exist anymore.

#include <iostream>
#include <memory>

using namespace std;

struct A
{
    int y;
    A(int x)
    {
        y = x;
    }
};

int main()
{
    auto a = make_shared<A>(1);
    cout << "a count: " << a.use_count() << endl; //prints a count: 1
    auto b = a->y;
    cout << "a count: " << a.use_count() << endl; //still prints a count: 1

    a.reset();

    cout << "a value: " << a << endl; //prints a value: 0
    cout << "b value: " << b << endl; //prints b value: 1

    return 0;
}
like image 993
John Avatar asked Aug 09 '26 23:08

John


1 Answers

auto b = a->y;

This will copy the value of y, so it's not a pointer to y, it's only a copy.

like image 190
moskalenko2k24 Avatar answered Aug 12 '26 23:08

moskalenko2k24



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!