通过函数中的引用操作值的安全性
Safety of manipulating a value via a reference in a function
关于风格的简单问题。这两种方法都有效(如下所述),我想知道哪种方法被认为是更好/更安全的做法?我在添加时防止整数溢出,并为删除定义了一些功能。两个方法返回相同的结果。
#include <iostream>
#include <limits>
void safe_add(int&, int);
void safe_remove(int&, int);
int main() {
int x = 50;
safe_add(x, std::numeric_limits<int>::max());
return 0;
}
/*
* Adds two integers while protecting against overflow.
* int& target is manipulated directly in this function
*/
void safe_add(int& target, int amount) {
if(target > 0 && amount > std::numeric_limits<int>::max() - target) {
target = std::numeric_limits<int>::max();
} else if(amount > 0) { //a pos int that won't cause an overflow!
target += amount;
}
}
/*
* Removes "amount" from "target". This function protects
* against target becoming a negative.
* int& target is manipulated directly in this function.
*/
void safe_remove(int& target, int amount) {
if (amount > 0){
if (target >= amount) {
target -= amount; //guaranteed >= 0
}
else if (target < amount) {
target = 0; //simply remove the rest, i don't want negatives!
}
}
}
第二个方法只是返回计算的值,必须调用它来设置x
的值,如下所示:
#include <iostream>
#include <limits>
int safe_add(int, int);
int safe_remove(int, int);
int main() {
int x = 50;
x = safe_add(x, std::numeric_limits<int>::max());
return 0;
}
/*
* Returns the result of two integers added together,
* while protecting against int overflow.
* No parameters passed to this function are manipulated.
* Instead, an int should be assigned the result of this function.
*/
int safe_add(int target, int amount) {
if(target > 0 && amount > std::numeric_limits<int>::max() - target) {
target = std::numeric_limits<int>::max();
} else if(amount > 0) {
target += amount;
}
return target;//not affected if given a negative
}
/*
* Returns the result of "target - amount"
* The lowest value that target can be is 0.
* No parameters passed to this function are manipulated.
* Instead, an int should be assigned the result of this function.
*/
int safe_remove(int target, int amount) {
if (amount > 0){
if (target >= amount) {
target -= amount;
}
else if (target < amount) {
target = 0;
}
}
return target; //not affected if given a negative
}
你能打破任何一个吗?我错过了什么明显的东西吗?
因为您没有为您的函数提供文档/注释-从某人的POV只是看着函数现在的样子,那么第一种方法更清楚,参考表明参数可以修改。在第二种情况下,不确定返回的是什么。
但这只是一种观点,你的问题不能客观地回答,因为"安全"对不同的人有不同的意义。
就我个人而言,我不会像你那样花那么多精力去做这件事,相反,我会专注于使用一个具有良好定义的大小的数据类型,从cstdint相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 类与私有变量的其他类之间的线程安全性
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 读取和写入操作的线程安全性C++
- 正在重置文件安全性以继承MoveFile()操作之后的文件
- 通过函数中的引用操作值的安全性
- vector内存操作中的安全性