我可以调用一个虚函数来初始化一个基类子对象吗? [英] May I call a virtual function to initialize a base-class sub-object?

查看:194
本文介绍了我可以调用一个虚函数来初始化一个基类子对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道虚拟函数不应在构造函数中直接调用或间接调用,但这段代码运行正常。

我在这里是安全的吗?

I know that virtual functions should not be called either directly or indirectly in a constructor, but this code runs fine.
Is what I have here safe?

#include <iostream>
#include <string>

struct A {
    A (const std::string& name) {std::cout << name << std::endl;}
    virtual std::string tag() const = 0;
};

struct B: A {
    B() : A (tag()) {}
    virtual std::string tag() const override {return "B";}
};

int main() {
    B b; // Output gives "B\n"
}

(基于注释)是正确的解决方法?

If not, would the following (based on a comment) be a correct workaround?

// Replacement for class B:

struct B: A {
    B() : A (name()) {}
    virtual std::string tag() const override {return name();}
private:
    static std::string name() {return "B";}  // use static function
};


推荐答案

在构造函数和/或析构函数中调用虚拟成员一般确定。

Invoking virtual members in the constructor and/or destructor is generally ok.

这是一个不同的游戏在ctor初始化时,虽然所有基地都被初始化之前:

It's a different game in the ctor initializer though, before all bases are initialized:


12.6.2初始化基础和成员 [class.base.init]



..]

14可以为正在构建的对象调用成员函数(包括虚拟成员函数,10.3)。
类似地,正在构造的对象可以是 typeid 运算符(5.2.8)或 dynamic_cast (5.2.7)。但是,如果这些操作在 ctor-initializer (或在直接或间接从ctor-initializer调用的函数中)在基类的所有mem初始化器完成之前执行,操作结果未定义。

12.6.2 Initializing bases and members [class.base.init]

[...]
14 Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result of the operation is undefined.

这篇关于我可以调用一个虚函数来初始化一个基类子对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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