- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我创建了一个私有(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/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!