它可能会让一些程序员感到惊讶,并且尽管可能令人惊讶,但如果没有std::vector编译器的非标准支持,则无法实现.问题基本上在于能够在原始存储区域上执行指针运算.论文,p0593:出现在@ShafikYaghmour答案中的低级对象操纵对象的隐式创建,清楚地揭示了问题,并提出修改标准,以便更容易实现像容器和其他法律级编程技术的矢量.
然而,我想知道是否没有工作来实现一个类型,std::vector只相当于使用语言提供的内容而不使用标准库.
目标是在原始存储区域中逐个构造向量元素,并能够使用迭代器访问这些元素.这相当于std :: vector上的push_back序列.
为了解问题,请简单介绍std::vector在libc ++或libstdc ++ 中执行的操作:
void access_value(std::string x);
std::string s1, s2, s3;
//allocation
auto p=static_cast<std::string*>(::operator new(10*sizeof(std::string)));
//push_back s1
new(p) std::string(s1);
access_value(*p);//undefined behavior, p is not a pointer to object
//push_back s2
new(p+1) std::string(s2);//undefined behavior
//, pointer arithmetic but no array (neither implicit array of size 1)
access_value(*(p+1));//undefined behavior, p+1 is not a pointer to object
//push_back s2
new(p+2) std::string(s3);//undefined behavior
//, pointer arithmetic but no array …Run Code Online (Sandbox Code Playgroud)