I don't know why I can't find this somewhere online, but how can I access class instance member variables via a shared_ptr? The ways I've tried are commented out in the code below. They've both result in a segmentation fault.
I assume I could access the member variables by getting a raw pointer from the shared_ptr but I'd rather avoid that as it's not clean and negates the value of the shared_ptr What's a safe way to access these member variables?
#include <memory>
#include <iostream>
class Test{
public:
int x;
Test() : x(5){}
};
int main()
{
std::shared_ptr<Test> f;
// the following lines both produce seg faults
// std::cout << (*f).x << std::endl;
// std::cout << f->x << std::endl;
}
Your problem lies on the line std::shared_ptr<Test> f;. That line is similar to Test* f;; you declare a pointer to a Test, but you've not created a Test object for it to point to. You need to use
std::shared_ptr<Test> f(std::make_shared<Test>());
Then you can access members with f->x or (*f).x the same as you would a raw pointer.
You need to use:
std::shared_ptr<Test> f = std::make_shared<Test>();
Then you can access f->x. If you have C++11, you can remove some redundancy with the auto keyword and use:
auto f = std::make_shared<Test>();
Note that as a general rule, std::make_shared() is "better" than using
newdirectly.make_sharedallocates an instance of Test and the reference count needed for the shared_ptr in one memory allocation; usingnewmeans there will be two memory allocations--one for the new Test instance and one for the reference count used inside theshared_ptr. As with any generalization, there are times whenmake_sharedwill not work (e.g., when the class uses a custom allocator), but for this simple case, I think using make_shared is more helpful.
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