通过引用传递的强制转换整型
如果您有一个整型 t1 和一个通过引用获取可能更小的整型 t2 的函数,那么调用 function((t2)var_t1) 会有问题吗?
If you have an integral type t1 and a function getting a possibly smaller integral type t2 by reference, would it be problematic to call function((t2)var_t1) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当且仅当函数采用 const 引用时,才可以强制转换为
t2
,在这种情况下,转换为t2
会产生临时值> 可以绑定到它。由于这违背了引用整型类型的目的,我会假设该引用是非常量的,所以答案是:是的,这会有问题。需要明确的是,如果您转换为 t2,它甚至无法编译。
如果您希望
函数
仅修改t1
变量的部分内容,请在引用/指针上使用reinterpret_cast
。当然,理论上这会调用未定义的行为。It would be fine to cast to
t2
if and only if the function took a const reference, in which case the temporary produced by the cast tot2
could be bound to it.Since this defeats the purpose of a reference to an integral type I would assume that the reference is non-const, so the answer is: yes, it would be problematic. To be clear, it won't even compile if you cast to
t2
.If you want
function
to modify only parts of thet1
variable, use areinterpret_cast
on the reference/pointer. This will theoretically invoke undefined behaviour, of course.转换将创建一个临时变量,如果较小的类型不采用
const
引用,则您的代码将无法编译,因为临时变量无法绑定到非常量引用。如果它确实采用
const
引用,那么它会编译,但转换可能会导致溢出,这是将较大数据类型转换为较小数据类型时常见的问题。Casting will create a temporary, and if the smaller type does NOT take by
const
reference, your code would NOT compile, because the tempory cannot be bound to non-const reference.If it does take by
const
reference, then it would compile, but the casting might cause overflow which is the usual problem from casting bigger data type to smaller one.该函数必须采用 const 引用,否则无法编译。
The function would have to take a
const
reference, otherwise it wouldn't compile.由于您还标记了问题 C,在这种情况下“通过引用”仅意味着使用指针,因此您无法将
&
运算符应用于强制转换的结果。但是,您可以使用:请注意,这是有效的 C,但不是 C++,这是您不应混合使用 C 和 C++ 标签的原因之一...
Since you also tagged the question C, in which case "by reference" would just mean using a pointer, you cannot apply the
&
operator to the result of a cast. However, you could use:Note that is is valid C but not C++, one of the reasons you should not mix C and C++ tags...