c++ - 向上转换空指针是否会导致未定义的行为

标签 c++ language-lawyer implicit-conversion nullptr upcasting

我想知道以下代码是否会导致未定义的行为:

#include <cstddef>
#include <cstdio>

struct IA { 
  virtual ~IA() {}
  int a = 0;
};
struct IB {
  virtual ~IB() {}
  int b = 0;
};
struct C: IA, IB {};

int main() {
  C* pc = nullptr;
  IB* pib = pc;
  std::printf("%p %p", (void*)pc, (void*)pib);
}

最佳答案

向上转换一个空指针被定义为给你另一个空指针:

4.10p3:

A prvalue of type "pointer to cv D", where D is a class type, can be converted to a prvalue of type "pointer to cv B", where B is a base class of D. ... The null pointer value is converted to the null pointer value of the destination type.

关于c++ - 向上转换空指针是否会导致未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29850716/

相关文章:

c++ - Xcode 4 : why "Continue to current line" is grayed out?

c++ - 指针差异是否是在基于范围的 for 循环中查找 vector 中元素索引的有效方法?

c++ - 作为标准,C++ 是否禁止在单个类实例中存储成员函数?

c++ - 隐式转换为模板

scala - 向通用集合添加成对差异 - 隐式解析不起作用

c++ - for(;i<=m;i++) 是什么意思?

c++ - C++中 vector 的通用 vector

C++:将 wstring 转换为 double

c++ - C++17 中的 lambda 捕获

c++ - 强制 C++ 更喜欢带有隐式转换的重载而不是模板