Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access instance member variables via std::shared_ptr?

Tags:

c++

shared-ptr

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;

    }
like image 354
helloB Avatar asked Sep 01 '26 04:09

helloB


2 Answers

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.

like image 176
Miles Budnek Avatar answered Sep 03 '26 18:09

Miles Budnek


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 new directly. make_shared allocates an instance of Test and the reference count needed for the shared_ptr in one memory allocation; using new means there will be two memory allocations--one for the new Test instance and one for the reference count used inside the shared_ptr. As with any generalization, there are times when make_shared will not work (e.g., when the class uses a custom allocator), but for this simple case, I think using make_shared is more helpful.

like image 45
Phil Avatar answered Sep 03 '26 17:09

Phil



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!