This seems like a pretty dumb question, so please bear with me. I am using smart pointers in place of raw pointers in my programs. I am advised against using raw pointers or mixing the two as much as possible. I understand that as well. I am also aware that pointers should be used only went necessary.
class Foo{
private: int val;
public:
Foo(int v) :val(v){}
int getvalue() const { return val; }
};
std::shared_ptr<Foo> foo = std::make_shared(Foo(10));
int v;
//Option I
v=foo->getvalue();
//Option II
v=foo.get()->getvalue();
I feel option I is more correct as option II utilizes raw pointer. But using raw pointer may not hurt here as I am not allocating or deallocating.
Often I get confused with these two options. Which one is preferable? Are they just same? Thanks.
Raw pointers are not the enemy. We can't write any useful program in C++ without them in one shape or form. The problem is owning raw pointers. They don't have a clear ownership semantic associated with their type, and so it fall to the programmer to do the arduous task of managing the lifetime by hand. Don't fear passing a raw pointer around as a handle, if you need to.
Which brings us to the next point. Both methods you demonstrated rely on raw pointers. An overloaded operator-> must return a raw pointer (eventually) for us to apply member access on the object. In essence, the first version is equivalent to
v = foo.operator->() -> getvalue();
It operates exactly the same as the second form, just with syntactic sugar on top.
You should prefer the first form because it is shorter and readable. But it doesn't avoid raw pointers, that's impossible to avoid.
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