Home > Backend Development > C++ > Should I Pass shared_ptrs by Reference or by Value in C ?

Should I Pass shared_ptrs by Reference or by Value in C ?

Susan Sarandon
Release: 2024-11-02 14:39:02
Original
926 people have browsed it

Should I Pass shared_ptrs by Reference or by Value in C  ?

Passing Shared_Ptrs: Reference vs. Value

In C , when passing a shared_ptr (either the boost implementation or the C 11 STL), developers have the option to pass it by reference or by value. The question arises: which approach is more appropriate?

Const Reference Method

Passing by const reference (void foo(const shared_ptr& p)) has no performance advantage over passing by value. This misconception was addressed by C luminaries Scott Meyers, Andrei Alexandrescu, and Herb Sutter during the "Ask Us Anything" session at C and Beyond 2011.

Passing by Value Method

Passing by value (void foo(shared_ptr p)) is generally preferred for two reasons:

  1. No unnecessary overhead: Passing by value avoids the creation of a temporary reference, which would otherwise introduce unnecessary overhead.
  2. Consistency with semantics: Passing by value aligns with the semantics of other container types (e.g., vectors, lists), avoiding confusion in coding practices.

Alternative Approach

However, in specific scenarios where ownership needs to be shared, passing by value may be necessary. For instance, when transferring ownership between data structures or threads, passing by value can facilitate the transfer of ownership while ensuring proper memory management.

Conclusion

In general, passing a shared_ptr by const reference provides no tangible performance benefits and is not recommended. Passing by value is the preferred approach, ensuring consistency and avoiding unnecessary overhead.

The above is the detailed content of Should I Pass shared_ptrs by Reference or by Value in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template