0

I was wondering why my native pointer is still able to access my object after the memory should be freed?

#include <iostream>
#include <memory>
using namespace std;

class A 
{
public:
    int a_;
    double b_;

    A(int a, double b) : b_(b), a_(a)
    {}
};

int main() {

    auto s_ptr = make_shared<A>(3,3.3);
    A* n_ptr = s_ptr.get();

    cout << n_ptr->b_ << endl;

    s_ptr.reset();

    cout << n_ptr->b_ << endl;

    return 0;
}

The output is:

3.3
3.3

Maybe the memory is freed but still stores the same values. In this case, how can I verify if an object still exists?

Thanks!

Obol
  • 1
  • 1
    It's undefined behavior anyway. If the instance was deleted, that doesn't necessarily mean the memory where it resided is reset to zeroes or such. – πάντα ῥεῖ Sep 17 '15 at 08:10
  • 1
    Accessing deleted object is UB, and retrieving the same/expected value is a possible behavior for UB. – Jarod42 Sep 17 '15 at 08:10
  • *"how can I verify if an object still exists?"* `std::weak_ptr` (instead of raw pointer) may help in your case. – Jarod42 Sep 17 '15 at 08:12

0 Answers0