gpt4 book ai didi

c++ - C++ static_cast 结果的生命周期

转载 作者:行者123 更新时间:2023-11-28 02:44:27 25 4
gpt4 key购买 nike

我想知道 - cpp 中的转换结果实际上是什么?具体来说 - 他们的生命周期是多少?

考虑这个例子:

#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 创建一个在表达式的生命周期内存在的右值。也就是说,直到分号。参见 Value Categories .如果您需要传递对值的引用,编译器会将值放在堆栈上并传递该地址。否则,它可能会保留在寄存器中,尤其是在启用优化的情况下。

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

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

关于c++ - C++ static_cast 结果的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24902825/

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