C++11 标准容器是“最终的”吗?

发布于 2025-01-06 16:30:03 字数 200 浏览 0 评论 0原文

我们(应该)知道 C++ 标准库容器,包括 std::string,并不意味着可以继承。但尽管如此,C++98/03 确实允许我们这样做,即使它会导致错误。

既然 final 关键字可用,那些标准库容器是否被标记为 final 以防止继承的错误使用?

如果不是,那是为什么呢?

We (should) know that C++ standard library containers, including std::string, are not meant to be inherited from. But still, C++98/03 did allow us to do it even if it was leading to bugs.

Now that the final keyword is available, are those standard library container marked final to prevent bad use of inheritance with them?

If not, why is that?

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

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

发布评论

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

评论(2

玩世 2025-01-13 16:30:03

LWG 在最近于 2012 年 2 月 6 日至 10 日在科纳举行的会议上讨论了这个问题。这是 LWG 问题 2113

LWG 决定将 LWG 2113 标记为 NAD(不是缺陷),其理由是该标准已经明确指出现有类(例如容器和 std::string)无法通过实现标记为 Final 。

讨论包括这样一个事实:虽然从此类类派生可能会令人不悦,但在 C++98/03 中这样做显然是合法的。在 C++11 中使其非法会破坏太多代码。

更新

目前,当前工作草案被标记为最终

The LWG discussed this issue at the recent meeting in Kona Feb. 6-10, 2012. This is LWG issue 2113.

The LWG decided to mark LWG 2113 as NAD (not a defect), with the rationale that the standard is already clear that existing classes such as containers and std::string can not be marked final by the implementation.

The discussion included the fact that while it may be frowned on to derive from such classes, it is clearly legal to do so in C++98/03. And making it illegal in C++11 would break far too much code.

Update

At this time, no library types in the current working draft are marked final.

悲凉≈ 2025-01-13 16:30:03

std::string 似乎没有被标记为 Final,其他容器也没有。

我的猜测是,尽管通常不建议从它们派生,但没有人很确定如果禁止它会破坏多少工作代码。

另请注意,就其价值而言,final 从技术上讲并不是一个关键字——它是一个附加了特殊含义的标识符,但仅在特定情况下才有效。包含类似 int Final; 的代码Final = 1; 仍然有效。这主要是为了向后兼容——至少在新代码中,几乎可以肯定的是,仅将 final 用于特殊含义,而不是作为普通标识符使用。

std::string does not seem to be marked final, nor do the other containers.

My guess as to why would be that even though deriving from them isn't generally recommended, nobody was quite sure how much working code would break if it was prohibited.

Also note that, for what it's worth, final isn't technically a key word -- it's an identifier to which a special meaning is attached, but only under specific circumstances. Code that contained something like int final; final = 1; will still work. This is mostly for backward compatibility though -- at least in new code, it's almost certainly better to use final only for the special meaning, not as a normal identifier.

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