Home >Backend Development >C++ >Should Pass-by-Value Be the Default for Large Objects in Modern C ?
Rethinking Pass-by-Value in C 11
In the world of C , pass-by-value has traditionally been discouraged for large objects due to performance concerns. However, the introduction of Rvalue references and move constructors in C 11 opens up new possibilities for passing objects efficiently.
Is Pass-by-Value Now the Best Default?
According to industry expert Dave Abrahams, it's reasonable to pass large objects like std::vector and std::string by value if you need to make a copy within the function body. This allows the compiler to perform optimization, eliminating the need for explicit copying by the programmer.
Advantages:
Custom Objects:
For custom objects, pass-by-reference to const is still a viable option, as it provides flexibility and minimizes the risk of unintentionally modifying the original object.
Best Practices:
Example:
To implement the recommended pattern, valued constructors can be written as follows:
class T { U u; V v; public: T(U u, V v) : u(std::move(u)) , v(std::move(v)) {} };
The above is the detailed content of Should Pass-by-Value Be the Default for Large Objects in Modern C ?. For more information, please follow other related articles on the PHP Chinese website!