c++ static_cast结果的生命周期
Life time of a c++ static_cast result
我想知道- 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的安全性。
相关文章:
- 如何在共享库的整个生命周期内存储数据
- 如何理解句子的生命周期始于对e的评估
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了
- Go/C++gRPC客户端通道和存根生命周期
- 如何将"this"的生命周期移动到C++中的另一个对象中?
- 是否可以通过使用移动/交换 c++11 来延长返回的临时变量的生命周期
- 使用对象的生命周期作为设置器的安全性
- 临时人员的生命周期传递给函数
- 我想知道在构造函数中初始化变量时的生命周期
- Lua 用户数据生命周期管理
- 如何使用 epoll(void* event.data.ptr) 管理 Connection 的生命周期
- C++引用的生命周期
- 在堆栈上有一个对象,而不是在函数的整个生命周期内
- 在 Boost ASIO 服务器中处理生命周期
- C++ lambda 生命周期
- 使用互斥锁跟踪另一个应用的生命周期
- QSharedPointer 或 std::shared_ptr 的生命周期
- 来自async_resolve的 boost::asio::ip::tcp::resolver::iterator 的生命周期是多久?
- 如何调整属于类的唯一指针的字符数组的大小.它必须在程序的整个生命周期中保持活力
- 延长 std::tuple<int&,int> 的生命周期,方法是将其分配给 const std::tuple<int, int>&