繁体   English   中英

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

[英]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中定义好的大小的数据类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM