c++ static_cast结果的生命周期

Life time of a c++ static_cast result

本文关键字:生命 周期 结果 cast static c++      更新时间:2023-10-16

我想知道- cpp中的cast结果实际上是什么?具体来说,他们的寿命是多少?

考虑这个例子:

#include <iostream>
#include <stdint.h>
using namespace std;
class Foo
{
public:
    Foo(const int8_t & ref)
    : _ptr(&ref)
    {}
    const int8_t & getRef() { return *_ptr; }
private:
    const int8_t * _ptr;
};

enum Bar
{
    SOME_BAR = 100
};
int main()
{
    {
        int32_t value = 50;
        Foo x(static_cast<int16_t>(value));
        std::cout << "casted from int32_t " << x.getRef() << std::endl;
    }

    {
        Bar value = SOME_BAR;
        Foo x(static_cast<int16_t>(value));
        std::cout << "casted from enum " << x.getRef() << std::endl; 
    }
   return 0;
}
输出:

casted from int32_t 50
casted from enum 100

它工作-但它是安全的吗?对于整数,我可以想象编译器以某种方式转换一个"指针"到目标变量字节的所需部分。但是当你将int强制转换为float时会发生什么呢?

static_cast创建一个在表达式生命周期内存在的右值。也就是说,直到分号。参见值类别。如果需要传递对该值的引用,编译器将把该值放在堆栈上并传递该地址。否则,它可能会留在寄存器中,特别是在打开优化的情况下。

你使用它的方式,在你使用它的地方,static_cast是完全安全的。然而,在Foo类中,您保存了一个指向右值的指针。程序能正确执行只是运气问题。一个更复杂的例子可能会将这些堆栈位置用于其他用途。

编辑详细说明static_cast的安全性。