通过函数中的引用操作值的安全性

Safety of manipulating a value via a reference in a function

本文关键字:操作 安全性 引用 函数      更新时间:2023-10-16

关于风格的简单问题。这两种方法都有效(如下所述),我想知道哪种方法被认为是更好/更安全的做法?我在添加时防止整数溢出,并为删除定义了一些功能。两个方法返回相同的结果。

#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