c++ - 同样的代码在 Mac 上正确,在 Linux 上不正确

标签 c++ linux macos

<分区>

我遇到了一个让我陷入困境的问题(没有双关语意)。我试图说明重载运算符如何大大增强代码的可读性。为此,我编写了一个名为“cow”(无特殊含义)的简单类。当我在 Mac 上编译代码时,它编译干净并按预期执行。

在 Linux 机器 (Ubuntu) 上编译的完全相同的代码也可以干净地编译,但执行结果不正确。

在某个地方,我一定遗漏了一些明显的东西,但我没有看到。

代码如下:

#include <iostream>
#include <sstream>
using namespace std;

class cow {
public:
    cow();
    cow(int i);
    int add(int a);
    int add(string str);
    int get() const;
private:
    int i;
};

cow::cow() {
    i = 0;
}

cow::cow(int j) {
    i = j;
}

int cow::add(string str) {
    stringstream s;
    int num;
    s << str;
    s >> num;

    return i += num;
}

int cow::add(int a) {
    return i += a;
}

int cow::get() const {
    return i;
}

int main() {
    cow i(15);
    cout << i.get() << " : " << i.add(15) << " : " << i.add("-15.0");
    return 0;
}

编译 (g++ -Wall -o cow cow.cpp) 没有产生任何警告和错误,并创建了一个可执行文件。

在 Linux 机器上执行该程序会产生:

$ ./cow
15 : 15 : 0

在 Mac 上执行该程序会产生:

$ ./cow
15 : 30 : 15

Mac 上的 C++ 编译器是:

$ g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Linux 机器上的 C++ 编译器是:

$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

感谢任何关于导致此行为的建议,以及在 Linux 机器上修复它的方法!

谢谢,

基斯

最佳答案

你得到了一个未定义的行为,因为你在一个表达式中多次改变了实例的状态。根据 C++ 标准,您在这一行中对 i 的调用:

 cout << i.get() << " : " << i.add(15) << " : " << i.add("-15.0");

可以按任何顺序执行。 幸运的是 Mac 的编译器按照您的预期从左到右执行调用。 为了获得可靠的结果,您应该按顺序评估这些调用,例如:

auto a1 = i.get();
auto a2 = i.add(15);
auto a3 = i.add("-15.0);
cout << a1 << " : " << a2 << " : " << a3;

关于c++ - 同样的代码在 Mac 上正确,在 Linux 上不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47026519/

相关文章:

c++ - 带有 Crypto++ 库的 QT 控制台应用程序

ios - 使用 NSURLSession 进行单元测试

swift - 如何获取 Safari 中每个窗口的每个选项卡中所有打开的 URL?

c++ - Qt 工具提示在显示时将窗口置于最前面

linux - 我可以通过 Eclipse 使用 LLDB-MI 调试程序吗?

c++ - 使用 CAtlRegExp 匹配多个组

linux - 修剪 bash/sed 中的输入

python - 如何防止 LXML 错误 'failed to load external entity'

c++ - 为什么此代码会以某些角度返回框错误一侧的交点?

c++ - 使用 I2C 协议(protocol)从磁力计读取值