【发布时间】:2018-08-21 05:42:42
【问题描述】:
考虑一下:
class Base {};
class A : public Base {};
class B : public Base {};
class C : public Base {};
class D : public Base {};
class Obj
{
public:
Obj(const Obj&);
private:
A _a;
B _b;
C _c;
D _d;
Base *_current;
};
_current 始终指向 _a、_b、_c 或 _d 之一。 A、B、C 和 D 可以有不同的大小。我想实现Obj(const Obj&),以便副本的_current 本身指向适当的成员。
这种方法安全吗:
Obj::Obj(const Obj& obj) :
_a {obj._a},
_b {obj._b},
_c {obj._c},
_d {obj._d}
{
auto objAAddr = reinterpret_cast<const char *>(&obj._a);
auto objCurAddr = reinterpret_cast<const char *>(obj._current);
auto diff = objCurAddr - objAAddr;
auto myAAddr = reinterpret_cast<char *>(&_a);
_current = reinterpret_cast<Base *>(myAAddr + diff);
}
这里的“基”地址可以是 _a 以外的其他地址,例如 &_obj(然后将差异应用于 this)。
有没有更好/更清洁的选择?
【问题讨论】:
-
出于好奇,你想用这个模式来完成什么?
-
除了“安全吗?”问“它可读吗?”和“它可维护吗?”
-
coliru.stacked-crooked.com/a/649b11b1b76c977c 您可以使用指向成员函数的指针来简化复制分配。其他一切都变得复杂,但是...
-
我不知道如何用指向成员变量的指针做同样的事情,因为它不喜欢变量具有不同的类型,因为来自
Derived Obj::*的转换`Base Obj::* 是不允许的,因为可以尝试使用它来编辑原始数据。因此,我不得不求助于通用的 getter 函数。 -
为什么不使用 std::variant?
标签: c++ copy-constructor