【发布时间】:2025-12-29 06:45:09
【问题描述】:
我知道强类型别名规则。但是,cppreference 指出
实现不能声明额外的非静态数据成员,这些成员会占用与实部和虚部不相交的存储空间,并且必须确保类模板特化不包含任何填充。实现还必须确保对数组访问的优化考虑到指向 value_type 的指针可能为 std::complex 特化或其数组起别名的可能性。
这个要求是否允许像下面这样的代码是合法的,即使它不一定是道德的?
std::size_t numDoubles = 100;
double* a = (double*) std::malloc(numDoubles * sizeof(double));
std::complex<double>* b = reinterpret_cast<std::complex<double>*>(a);
DoSomethingWith(b[1]);
如果使用 new[] 生成双精度数组,答案会改变吗?
XY 问题说明:我正在尝试对可能不存在的第三方库提供的分配器进行抽象;该分配器返回一个 void*;我试图避免库中存在的细节泄漏到标题中。所以我的结构如下:
// foo.h
namespace impl {
void* Allocate(std::size_t numBytes);
}
template<typename T>
T* Allocate(std::size_t num) {
static_assert(std::is_pod_v<T>);
return static_cast<T*>(Allocate(num * sizeof(T)));
}
// foo.cpp
#if LIBRARY_PRESENT
void* impl::Allocate(std::size_t numBytes) { return LibraryAllocate(numBytes); }
#else
void* impl::Allocate(std::size_t numBytes) { return std::malloc(numBytes); }
#endif
不幸的是,std::complex 不是 POD,因为它有一个不平凡的默认构造函数。我希望我可以忽略这个问题。
【问题讨论】:
标签: c++ language-lawyer strict-aliasing