在std :: vector :: reserve后访问原始指针吗? [英] Is accessing the raw pointer after std::vector::reserve safe?

查看:256
本文介绍了在std :: vector :: reserve后访问原始指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是非常困难,但是下面的代码安全(即保证不会导致分段错误):

  std :: vector< int> vec(1); //确保& vec [0]有效
vec.reserve(100);
memset(& vec [0],0x123,sizeof(int)* 100); //安全吗?

我意识到这是丑陋的 - 我只想知道它是否技术上安全,漂亮。我想它的唯一用法是忽略存储在给定索引之外的值。



注意! 如何获取由vector :: reserve()分配的缓冲区的地址?涵盖相同的主题,但我更感兴趣,如果这是安全,如果有陷阱这样做。



EDIT:Original代码错误,用 memset 替换原始 memcpy



保留(),向量保证不重新分配存储,直到达到 capacity()



但是,标准没有说明向量实现可以在 size() capacity()。也许它可以用于一些内部数据 - 谁知道?



访问[0..size]之外的元素是未定义的行为。有 可以进行一些硬件检查。


This is pretty farfetched, but is the following code "safe" (i.e. guaranteed not to cause segmentation fault):

std::vector<int> vec(1); // Ensures that &vec[0] is valid
vec.reserve(100);
memset(&vec[0], 0x123, sizeof(int)*100); // Safe?

I realize that this is ugly - I'm only interested to know if it's technically safe, not "pretty". I guess its only usage could be to ignore values stored beyond a given index.

Note! How can I get the address of the buffer allocated by vector::reserve()? covers the same topic, but I'm more interested if this is safe and if there are pitfalls doing this.

EDIT: Original code was wrong, replaced original memcpy with memset.

解决方案

No, it is not safe.

After a reserve(), the vector is guaranteed not to reallocate the storage until the capacity() is reached.

However, the standard doesn't say what the vector implementation can do with the storage between size() and capacity(). Perhaps it can be used for some internal data - who knows? Perhaps the address space is just reserved and not mapped to actual RAM?

Accessing elements outside of [0..size) is undefined behavior. There could be some hardware check for that.

这篇关于在std :: vector :: reserve后访问原始指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆