正在投射std :: pair< T1,T2>常数& to std :: pair< T1 const,T2>常数&安全? [英] Is casting std::pair<T1, T2> const& to std::pair<T1 const, T2> const& safe?
问题描述
是否安全(在理论或实践中)reinterpret_cast
a std :: pair< T1,T2& const&
转换为 std :: pair< T1 const,T2> const&
,假设程序员没有故意做一些奇怪的事情,例如专门 std :: pair< T1 const,T2>
p>
Is it safe (in theory or in practice) to reinterpret_cast
a std::pair<T1, T2> const &
into a std::pair<T1 const, T2> const &
, assuming that the programmer hasn't intentionally done something weird like specializing std::pair<T1 const, T2>
?
推荐答案
这不是可移植的。
std :: pair
需求在第20.3节中列出。第17.5.2.3条澄清
std::pair
requirements are laid out in clause 20.3. Clause 17.5.2.3 clarifies that
第18至30条和附录D没有规定类的表示,故意忽略类成员的规范。实现可以根据需要来定义静态或非静态类成员或两者,以实现第18至30条和附件D中所指定的成员函数的语义。
Clauses 18 through 30 and Annex D do not specify the representation of classes, and intentionally omit specification of class members. An implementation may define static or non-static class members, or both, as needed to implement the semantics of the member functions specified in Clauses 18 through 30 and Annex D.
这意味着实现包含部分专门化是合法的(虽然不可能),如:
This implies that it's legal (although incredibly unlikely) for an implementation to include a partial specialization such as:
template<typename T1, typename T2>
struct pair<T1, T2>
{
T1 first;
T2 second;
};
template<typename T1, typename T2>
struct pair<const T1, T2>
{
T2 second;
const T1 first;
};
这是明确的不兼容布局。其他变体包括可能在第一
和/或第二
之前包含额外的非静态数据成员。
which are clearly not layout-compatible. Other variations including inclusion of additional non-static data members possibly before first
and/or second
are also allowed under the rule.
现在,考虑布局已知的情况有点有趣。虽然Potatoswatter指出 DR1334 ,它声称 T
和 const T
不符合版面配置,标准提供足够的保证以获得大部分的方式:
Now, it is somewhat interesting to consider the case where the layout is known. Although Potatoswatter pointed out DR1334 which asserts that T
and const T
are not layout-compatible, the Standard provides enough guarantees to allow us to get most of the way anyway:
template<typename T1, typename T2>
struct mypair<T1, T2>
{
T1 first;
T2 second;
};
mypair<int, double> pair1;
mypair<int, double>* p1 = &pair1;
int* p2 = reinterpret_cast<int*>(p1); // legal by 9.2p20
const int* p3 = p2;
mypair<const int, double>* p4 = reinterpret_cast<mypair<const int, double>*>(p3); // again 9.2p20
但是这不适用于 std ::对
,因为我们不能应用9.2p20,而不知道第一
实际上是未指定的初始成员。
However this doesn't work on std::pair
as we can't apply 9.2p20 without knowing that first
is actually the initial member, which is not specified.
这篇关于正在投射std :: pair< T1,T2>常数& to std :: pair< T1 const,T2>常数&安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!