重载运算符<<返回ostream&

发布于 2024-12-12 06:26:03 字数 403 浏览 0 评论 0 原文

我在示例应用程序中有以下代码:

ostream& operator<< (ostream& os, const ReferenceTest& rt)
{
    os << rt.counter;  //In this scenario, rt has a public int called counter
}

我很惊讶地发现该代码使用 GCC 4.6.1 编译时没有出现问题。使用 Visual Studio 2010 时它会失败,原因是我预料到的,即我没有返回对 ostream 的引用。但是,为两个平台编译时程序的输出是相同的(我有一个简单的 main() 来写入测试输出)。

符合哪些标准?我在这里遗漏了一些明显的东西吗?

-德里克

I had the following code in a sample application:

ostream& operator<< (ostream& os, const ReferenceTest& rt)
{
    os << rt.counter;  //In this scenario, rt has a public int called counter
}

I was surprised to learn that this code compiled without issue using GCC 4.6.1. It fails when using Visual Studio 2010 for the reason I would have expected, namely that I'm not returning a reference to an ostream. However, the output for the program when compiled for the two platforms is identical (I have a trivial main() that writes test output).

Which is standards compliant? Am I missing something obvious here?

-Derek

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海里的那抹蓝 2024-12-19 06:26:03

您是否在启用警告的情况下编译?我收到警告:使用 g++ 控制到达非 void 函数的末尾

您当然不希望编译器在代码出现第一个错误时停止。你希望它一举抓住尽可能多的东西。为此,编译器必须修补有缺陷的代码,以便它可以继续执行。在这种情况下,补丁很明显:返回作为参数提供的流。

永远不要相信编译器免费提供的那些“修复”。它们绝不是免费的。而是修复您的代码。

并且始终在启用警告的情况下进行编译。

Did you compile with warnings enabled? I get warning: control reaches end of non-void function with g++.

You certainly don't want a compiler to stop at the first error in your code. You want it to catch as many as it can in one swell foop. To do this, the compiler has to patch your buggy code so it can press on. In this case, the patch is obvious: Return the stream provided as an argument.

Never trust those "fixes" supplied for free by the compiler. They are anything but free. Fix your code instead.

And always compile with warnings enabled.

心碎无痕… 2024-12-19 06:26:03

除了返回语句之外还缺少其他内容吗?缺少它是未定义的行为(对于这种简单的情况,我什至希望它是编译时错误)。可能会发生 os << 的返回值rt.counter 表达式恰好放置在整个运算符<< 预期返回值的位置,这使其工作只是偶然的。

Missing something other than the return statement? The lack of it is undefined behavior (I would even expect it to be a compile time error for such simple case). It may happen that the returned value from os << rt.counter expression happens to be placed at the same location where the return value for the whole operator<< is expected, making it work just by chance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文