通过引用传递的强制转换整型

发布于 2024-11-04 08:31:48 字数 75 浏览 0 评论 0原文

如果您有一个整型 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 技术交流群。

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

发布评论

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

评论(4

吝吻 2024-11-11 08:31:48

当且仅当函数采用 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 to t2 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 the t1 variable, use a reinterpret_cast on the reference/pointer. This will theoretically invoke undefined behaviour, of course.

も让我眼熟你 2024-11-11 08:31:48

转换将创建一个临时变量,如果较小的类型不采用 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.

夏日落 2024-11-11 08:31:48

该函数必须采用 const 引用,否则无法编译。

The function would have to take a const reference, otherwise it wouldn't compile.

岁月如刀 2024-11-11 08:31:48

由于您还标记了问题 C,在这种情况下“通过引用”仅意味着使用指针,因此您无法将 & 运算符应用于强制转换的结果。但是,您可以使用:

function((t2 [1]){ (t2)var });

请注意,这是有效的 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:

function((t2 [1]){ (t2)var });

Note that is is valid C but not C++, one of the reasons you should not mix C and C++ tags...

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