【发布时间】:2019-08-20 18:24:42
【问题描述】:
我目前在 Mac 和 Linux 中面临不同的行为问题。我在文件test_max.cpp 中有以下代码。
#include <iostream>
#include <algorithm>
float func(float a) {
float b = a;
return b;
}
int main() {
float a = 0.6, b = 1;
const auto& a1 = func(a);
const auto& b1 = func(b);
const auto& res1 = std::max(func(a), func(b));
const auto& res2 = std::max(a1, b1);
std::cout << "res1: " << res1 << std::endl;
std::cout << "res2: " << res2 << std::endl;
}
这就是我编译代码的方式。
g++ -std=c++11 -01 -o test_max test_max.cpp && ./test_max
在 Mac 上,它为 res1 和 res2 返回相同的值作为 1。但是,在 linux 上,它总是为 res1 返回 0。我不知道为什么。有人可以帮我吗?
【问题讨论】:
-
请提供minimal reproducible example 以重现您声称的不同行为。
-
如果定义了
__linux__,func1和func2可能都返回 0? -
只要您拒绝提供minimal reproducible example,您将无法得到有用的回复
-
不是
std::max坏了,而是你没有给我们看的代码 -
func1和func2返回什么?如果它们按值返回,则max_val可能是一个悬空引用,即 UB。这可以解释行为上的差异