gpt4 book ai didi

c++ - Vtable 和 *_vptr 创建时间

转载 作者:行者123 更新时间:2023-11-30 01:51:55 25 4
gpt4 key购买 nike

Vtable 和 *_vptr 由编译器在编译时创建。编译器什么时候创建它,是在执行构造函数代码之前还是之后,还是在为类的对象分配内存之前或之后?

我想清楚地知道为什么虚拟构造函数是不可能的。

最佳答案

虚构造函数的不存在与vtable/vptr的创建过程无关。事实上,vtable 概念本身就是一个实现细节(如何/如果使用 vtable 是实现定义的)

现在,虚拟构造函数会做什么?当动态类型不同于静态类型时,虚拟成员函数的本质是提供动态多态性。

但是构造函数知道对象的静态类型,它必须是实际(this)对象的类型:这里不涉及动态行为。


注意:

有设计模式,例如Virtual Constructor pattern ,它允许您动态地克隆一个对象,如果那是您真正想要的:

class Shape {
public:
virtual ~Shape() { } // A virtual destructor
virtual void draw() = 0; // A pure virtual function
virtual void move() = 0;
...
virtual Shape* clone() const = 0; // Uses the copy constructor
virtual Shape* create() const = 0; // Uses the default constructor
};

class Circle : public Shape {
public:
Circle* clone() const; // Covariant Return Types; see below
Circle* create() const; // Covariant Return Types; see below
...
};

Circle* Circle::clone() const { return new Circle(*this); }
Circle* Circle::create() const { return new Circle(); }

关于c++ - Vtable 和 *_vptr 创建时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25458788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com