std::basic_string has no non-const
data() method that returns
charT*. Is this intentional? Howard Hinnant suggests it was probably left out because it was simply never proposed (
in this SO answer). I plan on submitting the following defect report (unless revisions are suggested here) if this was not intentional and is something that should be corrected.
Thanks,
Michael Bradshaw
PROPOSED DEFECT REPORT:
Regarding [basic.string], std::basic_string<charT>::data() returns a const charT* [string.accessors] (21.4.7.1). While this method is convenient, it doesn't quite match std::array<T>::data() [array.data] (23.3.2.5) or std::vector<T>::data() [vector.data] (23.3.6.4), both of which provide two versions (that return T* or const T*). An additional data() method can be added to std::basic_string that returns a charT* so it can be used in similar situations that std::array and std::vector can be used. Without a non-const data() method, std::basic_string has to be treated specially in code that is otherwise oblivious to the container type being used.
Adding a charT* return type to data() would be equivalent to doing &str[0] or &str.front().
This requires a small change to std::basic_string's definition in [basic.string] (21.4) to add the method to std::basic_string, and another small change in [string.accessors] (21.4.7.1) to define the new method. Changes are marked with HTML ins/del tags and marked green/red (respectively).
PROPOSED CHANGES:
21.4 Class template basic_string [basic.string]
...
namespace std {
template<class charT, class traits = char_traits<charT>,
class Allocator = allocator<charT> >
class basic_string {
public:
...
// 21.4.7, string operations:
const charT* c_str() const noexcept;
<ins>
charT* data() noexcept;
</ins>
const charT* data() const noexcept;
allocator_type get_allocator() const noexcept;
...
21.4.7.1 basic_string accessors [string.accessors]
const charT* c_str() const noexcept;
const charT* data() const noexcept;
1 Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].
2 Complexity: constant time.
3 Requires: The program shall not alter any of the values stored in the character array.
<ins>
charT* data() noexcept;
4 Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].
5 Complexity: constant time.
6 Requires: The program shall not alter the value stored at p + size().
</ins>
allocator_type get_allocator() const noexcept;
<del>4</del><ins>7</ins> Returns: A copy of the Allocator object used to construct the string or, if that allocator has been
replaced, a copy of the most recent replacement.
referring n3797 (latest publicly available draft at time of writing)