-2

#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 でコンパイルすると、teachers[0] の vtable ポインターがゼロになります。また、uncle の vtable ポインターは、上書きされるのではなく、元の値を保持します。私の質問: なぜそのようになったのですか? CLEAN の回避策はありますか? 私は一緒に行くことができますuncle._vptr=ifather->_vptrか?オブジェクトをコピーする通常のルーチンは何ですか? バグを報告する必要がありますか?注: プラットフォームに依存しないオブジェクト全体をコピーする必要があります。これは、オブジェクト タイプの識別がどのように行われても、常にオブジェクトのデータ ブロック内にある必要があるためです。

記事

C++ オブジェクトが VPTr を失うのはなぜですか

私を助けませんでした、それは別の理由があるに違いありません。

4

1 に答える 1