Passing std:: or boost::shared_ptr as a reference to a funct

General discussion about C/C++

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

Passing std:: or boost::shared_ptr as a reference to a funct

Postby Fahrenheit » Fri Mar 30, 2012 4:06 am

I was suggested to replace in few places passing const shared_ptr by value to passing by reference (e.g. change const std::shared_ptr param to const std::shared_ptr& param) when I was checking my project with PVS-Studio (http://pvs-studio.viva64.com), the static code analysis tool.

I understand that for performance hot-spots it might be a good optimization as creating a temporary copy of shared_ptr requires updating reference counter which is a interlocked operation.

So the question is - how safe is this optimization? Are there any cases when it could not be used?

Any thoughts on this would be appreciated.
Fahrenheit
 
Posts: 2
Joined: Mon Mar 26, 2012 10:40 am

Re: Passing std:: or boost::shared_ptr as a reference to a funct

Postby a7031x » Tue Apr 02, 2013 6:38 am

Don't use the const std::shared_ptr& scenario. It's not thread safe, since the referece won't increase the innter reference counter of shared_ptr. The overhead of creating a shard_ptr from another is effective and can be ignored most of time.
a7031x
 
Posts: 7
Joined: Tue Apr 02, 2013 5:43 am


Return to General

Who is online

Users browsing this forum: No registered users and 1 guest