复制对象时的虚拟表 [英] Virtual tables when copying objects

查看:24
本文介绍了复制对象时的虚拟表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <string>
class A
{
public:
    A(int a) : _a(a) {}
    virtual ~A() {}
    virtual void f() const {std::cout << _a << std::endl;}
private:
    int _a;
};
class B : public A
{
public:
    B(int a, int b) : A(a), _b(b) {}
    virtual void f() const {std::cout << _b << std::endl;}
private:
    int _b;
};
int main()
{
    B b (1,2);
    A a (5);
    A& ref = a;
    ref = b;
    ref.f();
    return 0;
}

输出:

1

据我所知,在将派生(扩展)类对象复制到基类对象时,派生对象被剪切,仅复制基类数据.但我认为'ref'的虚拟表现在应该作为'b'的虚拟表所以'ref.f();'应该调用函数:

I understand that when copying derived (extended) class object to the base class object, the derived object is being cut and only the base class data copied. But i thought that the virtual table of 'ref' now should be as a virtual table of 'b' so 'ref.f();' should call the function:

void B::f() const {std::cout << _b << std::endl;}

但是复制后'ref'的vtbl仍然是A类的vtbl.为什么呢?谢谢.

But after the copying the vtbl of 'ref' remains to be the vtbl of class A. why? Thanks.

推荐答案

首先,虚拟表"不是标准的 C++ 概念.实现动态绑定和实现虚函数是一种高度实现特定的机制.

Firstly 'virtual table' is not a standard C++ concept. It is a highly implementation specific mechanism to implement dynamic binding and implement virtual functions.

话虽如此,

但我认为虚拟表'ref' 现在应该是一个虚拟的'b' 表所以 'ref.f();'应该打电话功能

But i thought that the virtual table of 'ref' now should be as a virtual table of 'b' so 'ref.f();' should call the function

这是不正确的.虚拟表是每个类而不是每个对象.每个对象只有 Vptr.

This is not correct. Virtual table is per class and not per object. It is only Vptr that is per object.

'ref' 的类型(由 typeid(ref).name 确认,如果你愿意的话)是 'A &'.当您分配 'ref = b' 时,将使用对象 'b' 作为参数调用 'A' 的隐式赋值运算符.该运算符只是盲目地将b"的A"子对象复制到ref"(即a")引用的当前对象中.因此,对象a"现在与b"的A"子对象具有完全相同的状态.

The type of 'ref' (as confirmed by typeid(ref).name if you so please) is 'A &'. When you assign 'ref = b' the implicit assigment operator of 'A' is called with object 'b' as the argument. This operator just blindly copies the 'A' subobject of 'b' into the current object referenced by 'ref' (which is 'a'). Hence object 'a' now has the exact same state as the 'A' subobject of 'b'.

如您所见,在整个很长的故事中,VTABLE 和 VPTR 根本不存在!

As you can see, in this whole very long story, VTABLE and VPTR does not exist at all!.

这篇关于复制对象时的虚拟表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆