Good day. I'm refreshing my C++ knowledge after not using it since the late 90s and am getting up-to-speed on new things. Today, my question is on shared pointers and structs.
Here's my code:
#include <memory>
struct A {
int x;
};
int main() {
shared_ptr<struct A> y;
y->x =0;
return 0;
}
compile string:
g++ -Wall -Wpedantic --std=gnu++11 -g test.cpp -o test
valgrind memcheck notes there's an "Invalid write of size 4" on line 11, which is y->x = 0
So, my question is: why is there an invalid write? My understanding--obviously faulty--is that the shared_ptr idiom will handle allocation and de-allocation of memory for the thing it's pointed to, and indeed this happens when I use it to point to primitive types and classes as far as I can tell, but this case of using it with a struct is tripping me up.
The real use case I'm trying to figure out is using a smart pointer to store a struct sockaddr_in, but I figure I should (re)learn to crawl before I learn to build smart pointers to objects defined in a time before smart pointers were a widely-accepted thing.
Thanks.
shared_ptr<struct A> y;
That's an empty pointer, which doesn't point to (or own) any object. You can't dereference it.
You'll need to create an object to be managed by the pointer, for example:
auto y = std::make_shared<A>();
std::shared_ptr<A> y {new A};
The first is usually preferred, since it can allocate memory more efficiently.
You still have to allocate your object with new or with std::make_shared
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