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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With