Generally I'd recommend passing by raw pointer if you can, as long as your function has no business concerning the lifetime of the object.
If for some reason your function needs the interface of the shared pointer, such as to store a copy locally inside of your object, then generally you should pass the shared pointer by reference. If you don't need a copy, you don't need a copy. Period. Passing by value as opposed to reference to certain types for [potential] efficiency is the special case, not the other way around, since in general you only logically want to just pass the object and not a copy of the object. In other words, don't look at it as saying "oh, it's not
that inefficient to pass by value, so I'll pass by value," as that's just silly since here you're not gaining anything logically by passing by value -- you're just needlessly copying the object for a call that doesn't need a copy of the object.
Quote:Original post by joanusdmentia
Quote:Original post by AndreasC
Or just create the smart pointer, and then send its "pointee" wherever it pleases you aslong as you know that the stack created wrapper will delete the pointee when it's time.
This is a *very* bad idea. What if somewhere down the track you think, 'hey, it'd be better if I held onto that pointer for later'? You're app would come crashing down because you tried to access memory that's already been deleted. This could be even more disastrous (and difficult to find) if that memory location just happens to have been allocated to another object and your other object mysteriously gets clobbered for no apparent reason.
I disagree. It's not a bad idea at all pending context. In fact, you do the equivalent all the time whenever you pass a stack-allocated object around by pointer or reference, whether it just be to a single function call or to be held by another object. If you know that your code does not own the allocated memory (shared or otherwise), and you know that the object is required to be alive for the lifetime of your code which contains the pointer, there is little reason to hold a shared pointer or weak pointer to the data as opposed to a raw pointer, short of possible debugging. Not only that, but I'd even go so far as to say that holding a raw pointer in those cases is
better, since holding a shared pointer only succeeds at needlessly exposing that segment of code to the implementation details regarding how the lifetime of the target object is managed, regardless of the fact that it has no business with the object's lifetime at all. All you're doing is exposing details, increasing dependencies, and making the code not work with objects allocated by other means.
Unless you plan on always holding a weak pointer and checking if it's alive every time you use it, for debugging purposes, I'd recommend using a raw pointer whenever you can in code segments which don't deal directly with the lifetime off the referenced object.