gpt4 book ai didi

c++ - 安全地检查变量的类型

转载 作者:行者123 更新时间:2023-11-30 03:12:48 25 4
gpt4 key购买 nike

对于系统,我需要将指针转换为 long,然后将 long 转换回指针类型。你可以猜到这是非常不安全的。我想做的是使用 dynamic_cast 进行转换,所以如果我混合它们,我将得到一个空指针。此页面显示 http://publib.boulder.ibm.com/infocenter/lnxpcomp/v7v91/index.jsp?topic=/com.ibm.vacpp7l.doc/language/ref/clrc05keyword_dynamic_cast.htm

The dynamic_cast operator performs type conversions at run time. The dynamic_cast operator guarantees the conversion of a pointer to a base class to a pointer to a derived class, or the conversion of an lvalue referring to a base class to a reference to a derived class. A program can thereby use a class hierarchy safely. This operator and the typeid operator provide run-time type information (RTTI) support in C++.

如果它为 null,我想得到一个错误,所以我编写了自己的动态转换

template<class T, class T2> T mydynamic_cast(T2 p)
{
assert(dynamic_cast<T>(p));
return reinterpret_cast<T>(p);
}

使用 MSVC 我收到错误“错误 C2681:‘long’:dynamic_cast 的表达式类型无效”。事实证明这只适用于具有虚函数的类......WTF!我知道动态转换的重点是向上/向下转换继承问题,但我也认为它是动态解决类型转换问题。我知道我可以使用 reinterpret_cast 但这并不能保证相同类型的安全。

我应该使用什么来检查我的类型转换是否相同?我可以比较这两个 typeid,但是当我想将派生类型转换为它的基数时,我会遇到问题。那么我该如何解决呢?

最佳答案

dynamic_cast 只能在通过继承相关的类之间使用。要将指针转换为 long 或反之,您可以使用 reinterpret_cast。要检查指针是否为空,您可以assert(ptr != 0)。但是,通常不建议使用 reinterpret_cast。为什么需要将指针转换为 long?

另一种选择是使用 union :

union  U { 
int* i_ptr_;
long l;
}

同样,union 也很少需要。

关于c++ - 安全地检查变量的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/311102/

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