C++标准是否要求std::allocator<T>的T不可为const/volatile/引用类型?
C++标准对std::allocator的模板参数限制
gcc、clang和MSVC都会拒绝以下代码:
#include <memory> #include <vector> int main() { auto _ = std::vector<int const>{}; // error auto _ = std::vector<int volatile>{}; // error auto _ = std::vector<int&>{}; // error }
C++标准明确要求std::allocator<T>的模板参数T不能是const/volatile限定类型,也不能是引用类型。
具体来说,标准规定std::allocator的适用前提是T必须是可完整类型,同时:
- cv限定类型(如
const int、volatile int)无法满足allocator对内存分配后对象构造、管理的基本需求——allocator需要能初始化和操作内存中的对象,而const限定的对象初始化后无法被修改,volatile限定会带来额外的访问限制,不符合allocator的设计目标; - 引用类型(如
int&)本质是对象的别名,不是独立的对象实体,allocator无法为引用分配内存(因为引用不需要存储,仅用于绑定已有对象),因此也被标准排除在外。
内容的提问来源于stack exchange,提问作者xmllmx
相关产品推荐
相关产品推荐

