Dereferencing a shared pointer and assigning to it


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");
}





You are making changes to the object managed by the pointer ( you are not making it manage a new object)
– M.M
Jun 29 at 2:47





Yes, so the above code is safe then? I don't end up modifying a temporary or something like that?
– Martin F
Jun 29 at 2:51





Yes this is all fine
– M.M
Jun 29 at 3:05





As an aside, consider using auto more. Repetition is error-prone.
– Deduplicator
Jun 29 at 8:39


auto





@MartinF "modifying a temporary" What about it? Would that be bad?
– curiousguy
2 days ago




2 Answers
2



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



It is fine to do it but I would use the shared_ptr::get() operator in order to be more obvious regarding the fact that we are not using a raw pointer.


shared_ptr::get()


void foo()
{
std::shared_ptr<std::string> sharedPtr = std::make_shared<std::string>();
bar(*sharedPtr.get());
}





Why would you want to go out of your way to call out that you are using a smart-pointer?
– Deduplicator
Jun 29 at 8:38





I am not going out of my way, I am just using the default operator when returning the stored pointer. Anyway, it is more a question of taste for me
– marti_dms
Jun 29 at 8:47





You are using an extraneous .get(). That is going out of your way.
– Deduplicator
Jun 29 at 9:27


.get()






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Possible Unhandled Promise Rejection (id: 0): ReferenceError: user is not defined ReferenceError: user is not defined