简体   繁体   English

C ++:为什么引入std :: vector :: data成员函数?

[英]C++: Why is std::vector::data member function introduced?

I was looking at the STL's vector container from below link. 我从下面的链接查看STL的向量容器。 And it is mentioned that one of the new member functions added (with C++11) to this container is vector::data , which returns a pointer to the memory array used internally. 并提到,此容器中添加的新成员函数(与C ++ 11一起)是vector::data ,该函数返回指向内部使用的内存阵列的指针。

http://www.cplusplus.com/reference/vector/vector/data/ http://www.cplusplus.com/reference/vector/vector/data/

The example code given in above link also shows it usage, but it seemed that all that could be done with iterators too. 上面链接中给出的示例代码也显示了它的用法,但是似乎所有这些事情也可以通过迭代器完成。

Is there any specific reason for introduction of this member function? 引入此成员函数是否有任何特定原因?

from the comments: 从评论:

  • std::vector is a ContiguousContainer and can be accessed by pointers. std :: vector是一个ContiguousContainer ,可以通过指针进行访问。
  • access by pointer can be needed by C-like functions 类似C的函数可能需要通过指针进行访问

There is potential for failure: 存在失败的可能性:

  • deleting the pointer, will make the vecotr invalid and will create problems when the vector is destroyed. 删除指针,将使向量无效,并且在破坏向量时会产生问题。

  • everything that leads to reallocation of the underlying data in vector (like adding elements or shrinking) will make the pointer to a dangling pointer. 导致将基础数据重新分配到向量中的所有内容(例如添加元素或缩小)都会使指针指向悬空指针。 (As pointed out in the comments, this is also true for iterators and references) (正如评论中指出的那样,对于迭代器和引用也是如此)

I think the data() function was introduced for completeness of interface and convenience. 我认为引入data()函数是为了实现界面的完整性和便利性。

This way we do not need to resort to the ugliness of &vec[0] or &vec.front() . 这样,我们就不必诉诸&vec[0]&vec.front()的丑陋之处。

Moreover, getting a pointer to the underlying data is useful in many applications, like interfacing with C code or some external libraries, or in embedded contexts for example. 此外,在许多应用程序中(例如与C代码或某些外部库进行接口)或在嵌入式上下文中,获取指向基础数据的指针都是有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM