- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个简单的多态继承:
struct Base
{
virtual void exec() { std::cout << "base" << std::endl; }
virtual ~Base() { }
};
struct Derived1 : public Base
{
void exec() override { std::cout << "derived1" <<std::endl; }
};
struct Derived2 : public Base
{
void exec() override { std::cout << "derived2" << std::endl; }
};
我还有一个模板Wrapper
存储一些通用数据的类:
template<typename T> struct Wrapper : public T
{
bool b{true};
};
我可以安全地从 Wrapper<Derived1>
转换吗?至 Base
来自 Base
至 Wrapper<Derived1>
使用以下转换?
template<typename T> auto& asWrapper(T& mX)
{
return static_cast<Wrapper<T>&>(mX);
}
template<typename T, typename TWrapper> auto& asT(TWrapper& mX)
{
return reinterpret_cast<T&>(mX);
}
似乎可行的示例:
int main()
{
auto d1 = std::make_unique<Wrapper<Derived1>>();
auto d2 = std::make_unique<Wrapper<Derived2>>();
Base* bd1 = d1.get();
Base* bd2 = d2.get();
bd1->exec();
bd2->exec();
auto& bl1 = asWrapper(*bd1);
auto& bl2 = asWrapper(*bd2);
std::cout << bl1.b << " " << bl2.b << std::endl;
bl1.b = false;
std::cout << bl1.b << " " << bl2.b << std::endl;
bl2.b = false;
std::cout << bl1.b << " " << bl2.b << std::endl;
asT<Derived1>(bl1).exec();
asT<Derived2>(bl2).exec();
return 0;
}
可执行示例:http://ideone.com/MRy9Hy
这似乎可行,但我不相信这种方法的安全性。它符合标准吗?它会导致未定义的行为吗?
最佳答案
N4140 [expr.static.cast]/2:
An lvalue of type “cv1
B
,” whereB
is a class type, can be cast to type “reference to cv2D
,” whereD
is a class derived (Clause 10) fromB
, if a valid standard conversion from “pointer toD
” to “pointer toB
” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, andB
is neither a virtual base class ofD
nor a base class of a virtual base class ofD
. The result has type “cv2D
.” An xvalue of type “cv1B
” may be cast to type “rvalue reference to cv2D
” with the same constraints as for an lvalue of type “cv1B
.” If the object of type “cv1B
” is actually a subobject of an object of typeD
, the result refers to the enclosing object of typeD
. Otherwise, the behavior is undefined.
所以你的函数aswrapper
仅当 T&
时才定义行为传递给它实际上是指一个T
Wrapper<T>
的基础对象.示例程序中的两个调用都将 Base&
至 Wrapper<Base>&
, 但两个参数实际上都不是 Wrapper<Base>&
的基础对象,因此结果行为是未定义的。
[expr.reinterpret.cast]:
...
7 An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue
v
of object pointer type is converted to the object pointer type “pointer to cvT
”, the result isstatic_cast<cv T*>(static_cast<cv void*>(v))
. Converting a prvalue of type “pointer toT1
” to the type “pointer toT2
” (whereT1
andT2
are object types and where the alignment requirements ofT2
are no stricter than those ofT1
) and back to its original type yields the original pointer value....
11 A glvalue expression of type
T1
can be cast to the type “reference toT2
” if an expression of type “pointer toT1
” can be explicitly converted to the type “pointer toT2
” using areinterpret_cast
. The result refers to the same object as the source glvalue, but with the specified type. [ Note: That is, for lvalues, a reference castreinterpret_cast<T&>(x)
has the same effect as the conversion*reinterpret_cast<T*>(&x)
with the built-in&
and*
operators (and similarly forreinterpret_cast<T&&>(x)
). —end note ] No temporary is created, no copy is made, and constructors (12.1) or conversion functions (12.3) are not called.
所以 asT<T>(WrapperT& foo)
相当于*reinterpret_cast<T*>(&foo)
相当于*static_cast<T*>(static_cast<void*>(&foo))
.指向 Wrapper<Base>
的指针当然可以转换为 void*
根据 [expr.static.cast]/4:
An expression
e
can be explicitly converted to a typeT
using astatic_cast
of the formstatic_cast<T>(e)
if the declarationT t(e);
is well-formed, for some invented temporary variablet
(8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expressione
is used as a glvalue if and only if the initialization uses it as a glvalue.
因为任何指针类型都隐式转换为 void*
每 [conv.ptr]/2:
A prvalue of type “pointer to cv
T
,” whereT
is an object type, can be converted to a prvalue of type “pointer to cvvoid
”. The result of converting a non-null pointer value of a pointer to object type to a “pointer to cvvoid
” represents the address of the same byte in memory as the original pointer value. The null pointer value is converted to the null pointer value of the destination type.
那个void*
可以通过 [expr.static.cast]/13 转换为任何对象指针类型:
A prvalue of type “pointer to cv1
void
” can be converted to a prvalue of type “pointer to *cv*2T
,” whereT
is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. The null pointer value is converted to the null pointer value of the destination type. If the original pointer value represents the addressA
of a byte in memory andA
satisfies the alignment requirement ofT
, then the resulting pointer value represents the same address as the original pointer value, that is,A
. The result of any other such pointer conversion is unspecified. A value of type pointer to object converted to “pointer to cvvoid
” and back, possibly with different cv-qualification, shall have its original value.
鉴于上述asT
格式正确——你已经知道了,因为编译器没有诊断它。但是,自Wrapper<Base>
对齐以来,示例程序中的两个调用具有未指定的行为。可能不满足 Derived1
的对齐要求或 Derived2
.即使满足了对齐要求,对exec
的调用很可能会违反 3.10/10 中的严格别名限制,因为您正在处理可能是 Wrapper<Base>
的对象表示形式的内容。就好像它是一个 Derived
.
用reinterpret_cast
写的事实上,asT<Base>(Wrapper<Base>&)
甚至有未定义的行为。自Wrapper<Base>
以来,当然满足了对齐要求。源自 Base
, 但实际上使用返回的 glvalue 访问内存只有在 Wrapper<Base>
的地址时才具有定义的行为与其Base
的地址相同子对象。如果 Wrapper<Base>
就是这种情况是标准布局,但其他对象布局未指定。
该程序多次出现未定义的行为。正常工作的外观是实现选择的对象布局的产物。
关于c++ - 使用 reinterpret_cast 和 static_cast 模拟具有多态参数的模板中的协变和逆变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28810470/
我最近了解到 C++ 标准包含“严格的别名规则”,它禁止通过不同类型的变量引用相同的内存位置。 但是,该标准确实允许 char 类型合法地别名任何其他类型。这是否意味着 reinterpret_cas
我需要将一段代码从 C++ 转换为 VB6。 具体来说,这个: reinterpret_cast(reinterpret_cast(lParam)->hwndParent) 有人能告诉我这在 VB6
我正在编写与对齐相关的代码,如果给定的指针正确对齐,却没有标准的功能测试,这让我感到非常惊讶。 似乎互联网上的大多数代码都使用(long)ptr或 reinterpret_cast(ptr)测试对齐,
这个问题在这里已经有了答案: Why is reinterpret_cast not constexpr? (2 个答案) 关闭去年。 我遇到了以下错误: class NormalClass { p
我recently learned通过 reinterpret_casting 其地址将 POD 重新解释为不同的 POD 是未定义行为。所以我只是想知道 reinterpret_cast 的潜在用例
考虑以下程序: struct A{}; int main() { A a; A b = a; A c = reinterpret_cast(a); } 编译器 (g++14)
我recently learned通过 reinterpret_casting 其地址将 POD 重新解释为不同的 POD 是未定义行为。所以我只是想知道 reinterpret_cast 的潜在用例
它为什么会存在?在什么情况下它不会导致严格的别名违规,在哪些情况下会导致? 我的意思是,如果你在两个不兼容的类型之间进行转换,并且该转换的结果是唯一指向它在整个程序中使用的内存的指针,那么在假设没有其
这两个cast语句是一样的吗?它们产生相同的结果。 const std::int16_t i = 3; char a[ 2 ]; *reinterpret_cast(a) = i; reinterp
我已经编写了 MyString 和 MyStringConst 类。现在我需要不时地将 MyString 作为 MyStringConst 传递,因此重载强制转换运算符。这是我写的 MyString:
我有一个结构 S,它将两个类型为 T 的固定大小的数组打包在一起。 template struct S { array, 10> x1; array x2; }; 我想获取对大小为 2
如果我已将结构的成员复制到我的类中,我是否可以从我的类转换为结构? #include #include class Buffer { public: void * address;
#include struct A { int a; }; struct I1 : A { int a; }; struct I2 : A { int a; }; struct D : I1, I2
是否可以使用 reinterpret_cast 将 const 限定符仅添加到结构的一个成员。 #include std::pair test; std::pair& ctest = reinter
int main() { class_name object; object.method(); fstream file("writeobject.dat" , ios::o
当我注意到它的输出完全错误时,我正在测试一个简单的编译器。事实上,输出的字节顺序从小变大了。经过仔细检查,违规代码原来是这样的: const char *bp = reinterpret_cast(&
基本思想是创建一个可变大小的数组,在构造时固定,并在单个分配单元中创建另一个类,以减少开销并提高效率。分配缓冲区以适应数组,并使用另一个对象和新放置来构造它们。为了访问数组的元素和另一个对象,使用了指
#include struct I1 { virtual void nb1()=0; virtual ~I1(){} }; struct I2 { virtual void n
我刚刚在使用reinterpret_cast的代码中发现了一个错误,将其更改为dynamic_cast后,问题就消失了。然后,我尝试使用以下代码重现该行为: 1 #include 2 3
我想知道有没有一种不用大量复制就可以解决这个问题的好方法。 例如,假设我有一个字节缓冲区,我在其中保存了很多东西。我会正确地在其中保存 4 个字节的整数和 float 等。 现在,如果我的整数保存在缓
我是一名优秀的程序员,十分优秀!