In C, function parameters are exception-safe when passed by value, because the actual parameters retain their original values; passing by reference does not guarantee exception safety, and the actual parameters may be in an undefined state. Best practices recommend using pass-by-value to pass primitive types, lightweight objects, and parameters that do not affect the function call, and using pass-by-reference to pass large objects or parameters that require function modification.
C function exception safe parameter passing mechanism
In C, when calling a function, parameters can be passed by value or by Pass by reference. Passing by value means creating a copy of the actual parameter, while passing by reference uses the address of the actual parameter.
Pass by value
void foo(int x) { // 对 x 执行操作 }
Pass by reference
void foo(int& x) { // 对 x 执行操作 }
When a function throws an exception, the parameter passing mechanism has a real impact parameter status.
Pass-by-value exception safety
Pass-by-value is exception-safe because if the function throws an exception, the actual parameters will retain their original values. For example:
int main() { int x = 1; try { foo(x); } catch(...) { // x 仍为 1 } }
Pass-by-reference exception safety
Pass-by-reference does not guarantee exception safety. If a function throws an exception, the actual parameters may be in an undefined state because the function may have changed the reference. For example:
int main() { int x = 1; try { foo(x); } catch(...) { // x 可能不是 1 } }
Best Practices
To ensure exception safety, it is recommended to use pass-by-value in the following situations:
Use pass-by-reference when:
Practical Case
Consider a function that reads a stream and writes it to a file.
Pass the stream by value:
void writeToFile(std::istream& stream, std::ofstream& file) { std::string line; while (getline(stream, line)) { file << line << std::endl; } }
Pass the stream by reference:
void writeToFile(std::istream& stream, std::ofstream& file) { std::string line; while (getline(stream, line)) { file << line << std::endl; } stream.close(); // 按引用传递允许在函数退出时关闭流 }
By passing the stream by reference, we can ensure that the stream is always closed when the function exits, thus ensuring exceptions Occurs when the stream is in a closed state.
The above is the detailed content of C++ function exception safe parameter passing mechanism. For more information, please follow other related articles on the PHP Chinese website!