Joh*_*man 2 c++ oop inheritance memcpy
我有这个代码:
#include <iostream>
#include <string>
#include <cstring>
class Animal
{
public:
Animal(const std::string &name) : _name(name)
{
}
virtual void Print() const = 0;
virtual ~Animal() {}
protected:
std::string _name;
};
class Dog : public Animal
{
public:
Dog(const std::string &name, const std::string &dogtype) : Animal(name), _dogtype(dogtype)
{
Print();
}
void Print() const
{
std::cout << _name << " of type " << _dogtype << std::endl;
}
private:
std::string _dogtype;
};
class Cat : public Animal
{
public:
Cat(const std::string &name, int weight) : Animal(name), _weight(weight)
{
Print();
}
virtual void Print() const
{
std::cout << _name << " of weight " << _weight << std::endl;
}
virtual ~Cat(){}
private:
int _weight;
};
class Tiger : public Cat
{
public:
Tiger(const std::string &name, int weight, double speed) : Cat(name, weight), _speed(speed)
{
Print();
}
void Print() const
{
std::cout << _name << " speed " << _speed << std::endl;
}
virtual ~Tiger(){std::cout << "Tiger's dtor" << std::endl;}
private:
int _speed;
};
int main()
{
Animal *a = new Tiger("theRealKing", 3, 40.5);
Cat *c = new Cat("silvester", 4);
memcpy(c, a, sizeof(Cat));
c->Print(); /// ------------------------
delete a;
delete c;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在行中:c-> Print():在c成为老虎之前的那一行所以为什么它给我打印这条线:Ross的速度为135081,Ross的速度为3,为什么存在内存问题?为什么它叫老虎的打印方法而不是猫?
Ben*_*igt 10
它不能一起工作.
使用memcpy这些对象产生未定义的行为,标准允许任何事情发生.
它本身并不是导致问题的继承,而是虚拟成员函数或自定义构造函数/析构函数的存在.这些使您的对象失去了使用时所需的简单可复制分类.memcpy
由于第二个原因,您的类不是简单的可复制的 - 它包含一个std::string不易于复制的类型的成员.
实际上,当您执行std::string子对象的按位复制时,最终会有两个指向同一内存的指针,并且两个string对象都会尝试释放此指针.这会使你的程序崩溃.如果memcpy在v-table上使用还没有提前完成.
但是当你混合优化时,甚至更奇怪的事情都会发生.这就是未定义行为的含义.