c++ - 从成员构造函数调用虚函数

标签 c++

我对以下行为感到好奇:

#include <iostream>
#include <string>
struct A;
struct B {
    std::string b;
    B(A& a);
};
struct A {
    B member;
    virtual std::string f() { return "Hello, World!"; }
    A() : member(*this) {}
};
B::B(A& a) : b(a.f()) {}
int main() {
    std::cout << A().member.b;
}

这是打印预期结果的必需吗?还是未定义的行为?

最佳答案

这是合法的。 §12.7 [class.cdtor]/p4:

Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class’s non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor’s or destructor’s class and not one overriding it in a more-derived class. If the virtual function call uses an explicit class member access (5.2.5) and the object expression refers to the complete object of x or one of that object’s base class subobjects but not x or one of its base class subobjects, the behavior is undefined.

UB 案例不适用于此。

关于c++ - 从成员构造函数调用虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25723345/

相关文章:

java - 通过 jni 将枚举 native 类型公开给 java?

c++ - QT creator和Designer的区别——起步QT

c++ - 为什么没有 std::stou?

c++ - 没有光照计算时我应该忽略顶点法线吗?

c++ - 在 C++ 中如何将一个数据结构中的数据复制到另一个数据结构?

c++ - Visual Studio 2012 构建挂起

c++ - 为什么将 char 指针流式传输到 cout 不打印地址?

c++ - C++中各种初始化程序之间的区别

c++ - 加载所有 DLL 函数

c++ - 是否有等同于 Python 的 "import bigname as b"的 C++?