Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing a shared pointer and assigning to it

Is it ok to dereference a shared pointer, assign and assign a new object to it like so:

void foo()
{
    std::shared_ptr<std::string> x =
            std::make_shared<std::string>();

    bar(*x); // is this fine?
    // x == bsl::string("WHATEVER")
}

void bar(string& y)
{
    y = string("whatever");
}
like image 215
Martin F Avatar asked Jun 29 '18 02:06

Martin F


People also ask

What does “dereferencing” a pointer mean in C++?

What does “dereferencing” a pointer mean in C/C++? Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. * (asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.

What is shared pointer in C++?

A shared pointer supports usual pointer dereferencing The shared pointer is, in fact, a class which has a raw pointer pointing to the managed object. This pointer is called stored pointer. We can access it

What is dereferencing in C++ server side?

C C++ Server Side Programming Programming Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.

What is the difference between a shared pointer and unique pointer?

Therefore, the memory that a shared pointer takes is more than a raw pointer and a unique pointer. So, if a vector of a million pointers should be created, probably unique pointers are a better choice.


1 Answers

Yes, this is valid. Operator * returns the result of dereferencing the stored (raw) pointer.

Dereferencing a (raw) pointer does not make a copy or return a temporary: dereferencing a pointer when passing by reference

like image 128
VLL Avatar answered Oct 12 '22 22:10

VLL