Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing shared_ptr(this) into vector results in "free(): invalid pointer" error

I am trying to implement a class that can push a smart pointer to itself into a vector:

#include <memory>
#include <vector>

class A {
public:
    void pushme(std::vector<std::shared_ptr<A>> & vec) {
        vec.push_back(std::shared_ptr<A>(this));
    }
};

int main() {
    A test;
    std::vector<std::shared_ptr<A>> vec;
    test.pushme(vec);
    return 0;
}

This compiles nicely, but on execution I get an free(): invalid pointer error. Please help me understand what is going on here.

like image 726
murphy Avatar asked Aug 09 '26 22:08

murphy


1 Answers

A test;

This declares an object in function local scope. The object is automatically freed when it goes out of scope.

Only objects in dynamic scope (created with new) can be managed by std::shared_ptr. That's the whole purpose of std::shared_ptr -- to automatically call delete when the last shared pointer to an object goes away. And you can only delete something that has been allocated with new.

like image 133
Sam Varshavchik Avatar answered Aug 11 '26 13:08

Sam Varshavchik



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!