【发布时间】:2021-09-23 05:08:25
【问题描述】:
为什么这段代码在 C++ 中有效:
class Base
{
public:
Base() = default;
// base class stuff...
};
template<typename NumericType>
class Numeric : public Base
{
public:
Numeric() : m_value() {}
void setValue(NumericType value) { m_value = value; }
NumericType value() const { return m_value; }
private:
NumericType m_value;
};
int main()
{
auto integerPtr = new Numeric<int>();
Base *basePtr = integerPtr;
if (auto doublePtr = static_cast<Numeric<double>*>(basePtr)) {
doublePtr->setValue(6543423.634234);
std::cout << "Wow: " << doublePtr->value() << std::endl;
}
return 0;
}
老实说,我期待编译错误,或者至少 static_cast 会失败,但是这个代码示例可以编译、运行,甚至可以正常工作。
但是我想知道如果我们尝试设置一个大于需要超过 4 字节内存的值,这是否会导致未定义的行为(因为该对象专用于 int 类型(通常为 4 字节)但我正在尝试存储双)。
使用 MCVS2019 32 位编译。
【问题讨论】:
标签: c++ templates type-conversion