Home > Backend Development > C++ > Should Pass-by-Value Be the Default in C 11 for Large Objects?

Should Pass-by-Value Be the Default in C 11 for Large Objects?

Patricia Arquette
Release: 2024-12-02 17:35:11
Original
366 people have browsed it

Should Pass-by-Value Be the Default in C  11 for Large Objects?

Re-thinking Pass-by-Value in C 11

In traditional C , passing by value into functions incurred performance penalties for large objects. Hence, C programmers opted for pass-by-reference, improving speed but introducing complexities in ownership and memory management, especially for heap-allocated objects.

C 11 introduced Rvalue references and move constructors, enabling efficient pass-by-value for large objects like std::vector and std::string. This raises the question of whether pass-by-value should become the default for such types.

Passing by Value: A New Default?

According to Dave Abrahams, pass-by-value can be the preferred default if copying is necessary within the function. By allowing the compiler to handle the copying, programmers can avoid explicit copying operations:

void foo(T t) {
    // ...
}
Copy after login

Compared to passing by reference:

void foo(T const& t) {
    auto copy = t;
    // ...
}
Copy after login

Pass-by-value offers flexibility for the caller:

T lval;
foo(lval); // copy from lvalue
foo(T {}); // (potential) move from prvalue
foo(std::move(lval)); // (potential) move from xvalue
Copy after login

Exceptions to Pass-by-Value

While pass-by-value can be suitable for some types, passing by reference to const remains a reasonable option:

  • Objects that should not be copied: Passing a reference ensures that no unnecessary copy is made.
  • Large objects that are frequently passed by value: The copy operation can still be expensive, even with move semantics.
  • Objects transferred between threads: Passing by reference allows efficient thread synchronization.

The above is the detailed content of Should Pass-by-Value Be the Default in C 11 for Large Objects?. 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