gpt4 book ai didi

c++ - C++ 中的运行时运算符

转载 作者:可可西里 更新时间:2023-11-01 16:35:28 25 4
gpt4 key购买 nike

C++中编译时和运行时运算符的定义是什么?

我知道 sizeof() 是 C++ 中的编译时运算符,但哪些是运行时运算符?


( Originally posted for by bc90 ; 我不想浪费我在很明显他只想要 C 答案之前发布的答案。嘿,也许这可以帮助总有一天“澄清”某人的“疑惑”。)

最佳答案

事情没有那么简单。没有“运行时运算符列表”或“编译时运算符列表”。有运算符,其中许多可能被优化为由编译器“执行”,而不是作为要在运行时执行的操作编码到程序中。

最明显的是 sizeof,它从不需要延迟到程序执行。事实上,一般来说,作用于类型 的运算符可能被认为是不依赖于运行时信息的纯粹语义操作。再举一个例子,const_cast 绝对没有任何运行时相关性,因为 const 甚至不存在于您编译的程序中。 static_cast 可能会被优化,但这取决于相关转换运算符的作用。

可能不那么明显的是,许多调用算术运算符的表达式可能会被优化掉。

例如:

const int x = 2 + 4;

除非您的编译器非常非常愚蠢,否则不会在运行时执行该添加。但这是否使 operator+ 成为“编译时运算符”?没有。

函数调用运算符 () 只有在适用的 constexpr 规则适用,或者函数定义在与调用站点相同的翻译单元,并且足够简单。

虽然我们正在处理它,但 reinterpret_cast 取消了表达式作为 constexpr 的资格。这是相当不直观的,但根据 CWG issue #1384 中的基本原理:

Although reinterpret_cast was permitted in address constant expressions in C++03, this restriction has been implemented in some compilers and has not proved to break significant amounts of code. CWG deemed that the complications of dealing with pointers whose tpes [sic] changed (pointer arithmetic and dereference could not be permitted on such pointers) outweighed the possible utility of relaxing the current restriction.

我的观点是,真的,不值得为此制定一般规则:C++ 程序编译的过程不是那么简单。您必须根据具体情况检查您的程序在做什么。

但是,我非常感谢您尝试回答一个糟糕的考试问题。为此,我很同情你。

关于c++ - C++ 中的运行时运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30165196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com