这样做是否安全:
class Base { public: int x; };
class Derived : public Base { public: int y; };
Base b;
Derived d;
b.x = 1;
d.x = 2;
d.y = 3;
std::swap(b,d);
此时是否保证派生的信息 dy 仍然有效?换句话说,我只是在交换基础对象,但派生数据仍然有效,对吗?另外,这被认为是切片吗?
编辑:在评论中指出这不会编译。将 d 中的基础数据与 b 交换的最佳方法是什么?请记住,b 显然比我在示例中提出的要复杂得多。