Open furgalep opened 9 years ago
@simonlynen, @schneith, anyone else?
Isn't the reference counter screwed up when you pass shared pointer by reference?
I am following this suggestion: "Shortly, there is no reason to pass by value, unless there is multi-threading going on, but this needs to be considered separately." From: http://stackoverflow.com/a/8741626
Oh, I see. Ok when you assign to member directly.
Shouldn't there be also a method to make the refered object const?
std::shared_ptr<const Camera> getCamera() const;
How would that method look like if the member is a ´´´std::shared_ptr
About Q2:
getSharedCamera()
or getCameraShared()
?shard_ptr<const Camera>
is a totally different question. It is much more a question of the whole design. If that const was necessary (it won't be optional) you would know by the design part concerning how to get write access to a camera. Either it should be possible via a Frame or not. If you decide that it is clear which kind of getters you can have here.Again Q2: To be fast I would return const std::shared_ptr<Camera>&
rather than std::shared_ptr<Camera>
, and ideally make the getter inline (= don't prevent it by defining it in a cpp file), to have the optimizers optimize the reference to an pointer indirection.
Why would one want that extra copy into a temporary object (yielding ownership management overhead)? Move semantics or return value optimization is impossible here, as you return a member, which isn't a temporary object. Of course it that temporary is assigned to a local it will be moved but that is still less efficient than directly copying from a reference. And in some cases it won't be assigned, like e.g. in things like: frame->getCamera()->getStuff()
.
Of course multi threading can again change a lot here...
We use shared pointers for memory management but I still have some questions on what is the best use.
Let's say I have a class,
Frame
, that has a shared_ptr memberCamera
. The camera is shared among many frames. I have some questions about best practices:Questions:
Q1. What should the constructor take as an argument:
std::shared_ptr<Camera>
, orconst std::shared_ptr<Camera>&
, or something else?Q2. What should
getCamera()
return,std::shared_ptr<Camera>
, orconst std::shared_ptr<Camera>&
, orconst std::shared_ptr<const Camera>&
, or something else? Or should we have a const and a non-cost version. And should we name the non-const versiongetCameraMutable()
?Q3. What should
setCamera()
take as an argument:std::shared_ptr<Camera>
, orconst std::shared_ptr<Camera>&
, or something else?