本文介绍了为什么std :: vector :: data和std :: string :: data不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

向量的新方法 data()提供了一个const和非const版本。

不过string的 data / code>方法只提供一个const版本。

Vector's new method data() provides a const and non-const version.
However string's data() method only provides a const version.

我认为他们改变了 std :: string ,以便字符现在需要是连续的(如 std :: vector )。

I think they changed the wording about std::string so that the chars are now required to be contiguous (like std::vector).

code> std :: string :: data 刚刚错过了?或者是只允许const访问字符串底层字符的好理由。

Was std::string::data just missed? Or is the a good reason to only allow const access to a string's underlying characters?

注意: std :: vector :: data 有另一个不错的功能,它不是未定义的行为调用 data()在一个空向量。而& vec.front()是未定义的行为。

note: std::vector::data has another nice feature, it's not undefined behavior to call data() on an empty vector. Whereas &vec.front() is undefined behavior if it's empty.

推荐答案

在C ++ 98/03中,由于字符串常常被实现为COW,因此没有非const data()的好理由。如果引用计数大于1,则非const data()将需要一个副本。虽然可能,这在C ++ 98中并不可取/ 03。

In C++98/03 there was good reason to not have a non-const data() due to the fact that string was often implemented as COW. A non-const data() would have required a copy to be made if the refcount was greater than 1. While possible, this was not seen as desirable in C++98/03.

2005年10月,委员会在添加了const和非const data() vector 添加const和非const 映射。当时, string 没有被更改,因此取缔COW。但后来,通过C ++ 11,COW string 不再符合。 string spec在C ++ 11中也被收紧,因此它需要是连续的,并且总是有一个由 ](size())。在C ++ 03中,终止null只是由 operator [] 的const重载保证。

In Oct. 2005 the committee voted in LWG 464 which added the const and non-const data() to vector, and added const and non-const at() to map. At that time, string had not been changed so as to outlaw COW. But later, by C++11, a COW string is no longer conforming. The string spec was also tightened up in C++11 such that it is required to be contiguous, and there's always a terminating null exposed by operator[](size()). In C++03, the terminating null was only guaranteed by the const overload of operator[].

简单来说,对于C ++ 11 string ,非const data()看起来更合理。据我所知,从未提出过。

So in short a non-const data() looks a lot more reasonable for a C++11 string. To the best of my knowledge, it was never proposed.

更新

charT* data() noexcept;

在作者在2月份的杰克逊维尔会议上。

was added basic_string in the C++1z working draft N4582 by David Sankel's P0272R1 at the Jacksonville meeting in Feb. 2016.

很好的工作David!

Nice job David!

这篇关于为什么std :: vector :: data和std :: string :: data不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:15