gpt4 book ai didi

c++ - 在没有虚方法或父类(super class)的类中,假设(第一个成员变量的地址)== this 是否安全?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:39 25 4
gpt4 key购买 nike

我创建了一个私有(private) API,它假定类中第一个成员对象的地址与类的 this 指针相同......这样成员对象就可以简单地派生出指向该对象的指针它是的成员,而不必显式存储指针。

鉴于我愿意确保容器类不会从任何父类(super class)继承,不会有任何虚拟方法,并且执行此技巧的成员对象将是声明的第一个成员对象,将该假设对任何 C++ 编译器都有效,还是我需要使用 offsetof() 运算符(或类似运算符)来保证正确性?

换句话说,下面的代码在 g++ 下实现了我所期望的,但它能在任何地方运行吗?

class MyContainer
{
public:
MyContainer() {}
~MyContainer() {} // non-virtual dtor

private:
class MyContained
{
public:
MyContained() {}
~MyContained() {}

// Given that the only place Contained objects are declared is m_contained
// (below), will this work as expected on any C++ compiler?
MyContainer * GetPointerToMyContainer()
{
return reinterpret_cast<MyContainer *>(this);
}
};

MyContained m_contained; // MUST BE FIRST MEMBER ITEM DECLARED IN MyContainer
int m_foo; // other member items may be declared after m_contained
float m_bar;
};

最佳答案

目前的标准似乎只对 POD 类型保证这一点。

9.2.17

A pointer to a POD-struct object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [Note: There might therefore be unnamed padding within a POD-struct object, but not at its beginning, as necessary to achieve appropriate alignment. ]

然而,C++0x 标准似乎将这种保证扩展到“标准布局结构对象”

A standard-layout class is a class that:

— has no non-static data members of type non-standard-layout class (or array of such types) or reference,

— has no virtual functions (10.3) and no virtual base classes (10.1),

— has the same access control (Clause 11) for all non-static data members,

— has no non-standard-layout base classes,

— either has no non-static data members in the most-derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

— has no base classes of the same type as the first non-static data member.

A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.

这个假设很可能在实践中成立(前者不仅有这些区别,尽管这可能是故意的)?

关于c++ - 在没有虚方法或父类(super class)的类中,假设(第一个成员变量的地址)== this 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2624628/

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