【发布时间】:2015-12-13 23:12:18
【问题描述】:
我正在阅读this。该问题包含以下程序。
#include <iostream>
#include <cstdio>
#include <string>
int main()
{
using namespace std;
string myString = "Press ENTER to quit program!";
cout << "Come up and C++ me some time." << endl;
printf("Follow this command: %s", myString);
cin.get();
return 0;
}
我在 g++ 4.8.1 上尝试过,但编译失败。 g++ 4.8.1 给出以下诊断。
9 47 [Error] cannot pass objects of non-trivially-copyable type 'std::string {aka class std::basic_string<char>}' through '...'
9 47 [Warning] format '%s' expects argument of type 'char*', but argument 2 has type 'std::string {aka std::basic_string<char>}' [-Wformat=]
这个错误是什么意思?该程序是否应该编译成功?哪个编译器是正确的(g++ 或 MSVS 2010)?为什么 MSVS 2010 接受此代码?代码在 MSVS 2010 上编译时会调用未定义的行为吗?
令人惊讶:我在使用 g++ 5.0 的 ideone 上进行了尝试,令人惊讶的是它编译和运行良好。 (见现场演示here.)。当我编译这段代码时,g++ 5.2.0 会发出警告。 (见现场演示here)。为什么它在 ideone 上编译得很好,但在 g++ 4.8.1 上却失败了? g++ 4.8.2(给出与 g++ 4.8.1、4.9.0、4.9.1、4.9.2 相同的诊断(给出错误而不是警告)。g++ 5.1.0 给出警告但程序仍然编译和运行良好。
为什么不同版本的 g++ 在编译上述程序时表现不同?这是 g++ 中的错误吗? Clang 也拒绝编译此代码以响应@TemplateRex 给出的答案
【问题讨论】:
-
它真的运行良好吗?两个现场演示似乎都没有正确显示
myString的内容。 -
它给出了错误,因为您正在做一些不允许的事情,即使用带有旧 C 函数的 C++ 对象,这根本不可能。
-
@JoachimPileborg:那么为什么它在 g++ 5.1.0、5.2.0 上编译成功而没有任何错误?
-
@StillLearning:这不是重复的。如果它是重复的,那么我在发布这个问题时不会链接那个问题。
-
另见stackoverflow.com/questions/10083844/…,它专门解释了为什么不同版本的行为可能不同。
标签: c++ visual-studio-2010 c++11 g++ compiler-bug