小编Ohn*_*hel的帖子

为什么复制对象时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
}
Run Code Online (Sandbox Code Playgroud)

使用 gcc 编译时,teachers[0] 的 vtable 指针为零。叔叔的 vtable 指针也保持其原始值而不是被覆盖。我的问题:为什么会这样?有干净的解决方法吗?我uncle._vptr=ifather->_vptr …

c++ internals vptr

-2
推荐指数
1
解决办法
806
查看次数

标签 统计

c++ ×1

internals ×1

vptr ×1