为什么在复制对象时丢弃了vptr?

时间:2014-01-22 13:30:15

标签: c++ internals vptr

实施例

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>

struct father
{
    int variable;
    father(){variable=0xEEEEEEEE;};
    virtual void sing(){printf("trollolo,%x\n",variable);}
    ~father(){};
};
struct son:father
{
    son(){variable=0xDDDDDDDD;};
    virtual void sing(){printf("trillili,%x\n",variable);}
    ~son(){};
};
int main()
{
    father * ifather=new(father);
    son * ison=new(son);
    father uncle;
    father * iteachers;

    *((long long*)&uncle)=0xDEAF;
    iteachers=(father*)malloc(20*sizeof(father));

    //ineffective assignments
    iteachers[0]=*ifather;
    uncle=*ifather;

    ifather->sing();//called to prevent optimization
    ison->sing();//only to prevent optimization

    std::cout.setf(std::ios::hex);
    std::cout<<"father:"<<*((long long*)ifather)<<","<<std::endl;
    std::cout<<"teacher0:"<<*((long long*)&(iteachers[0]))<<","<<std::endl;
    std::cout<<"uncle:"<<*((long long*)&uncle)<<","<<std::endl;
    std::cout<<"(son:"<<*((long long*)ison)<<"),"<<std::endl;

//  uncle.sing();//would crash
}

使用gcc编译时,教师[0]的vtable指针为零。 另外,叔叔的vtable指针保持其原始值而不是被覆盖。 我的问题:为什么会这样? 是否有CLEAN解决方法?我可以使用uncle._vptr=ifather->_vptr并且仍然可移植吗?复制对象的ORDINARY例程是什么?我应该提交错误吗? 注意:它应该复制整个对象平台 - 独立,因为无论如何识别对象类型,因为它应该始终在对象的数据块内!

文章

Why does my C++ object loses its VPTr

没有帮助我,这必须有不同的原因。

1 个答案:

答案 0 :(得分:4)

据我了解,基本上问题是这段代码是否是

#include <iostream>
using namespace std;

struct Base
{
    virtual void sing() { cout << "Base!" << endl; }
    virtual ~Base() {}
};

struct Derived: Base
{
    void sing() override { cout << "Derived!" << endl; }
};

auto main()
    -> int
{
    Base* p = new Derived();
    *p = Base();
    p->sing();      // Reporting "Base" or "Derived"?
}

应报告“基础”或“衍生”。

简而言之,赋值不会改变对象的类型

因此,它报告“派生”。