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) { // ... }
Compared to passing by reference:
void foo(T const& t) { auto copy = t; // ... }
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
Exceptions to Pass-by-Value
While pass-by-value can be suitable for some types, passing by reference to const remains a reasonable option:
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!