2391. basic_string is missing non-const data()

Section: 24.3.2 [basic.string] Status: Resolved Submitter: Michael Bradshaw Opened: 2014-05-27 Last modified: 2017-03-13

Priority: 3

View other active issues in [basic.string].

View all other issues in [basic.string].

View all issues with Resolved status.


Regarding 24.3.2 [basic.string], std::basic_string<charT>::data() returns a const charT* [string.accessors]. While this method is convenient, it doesn't quite match std::array<T>::data() [array.data] or std::vector<T>::data() [vector.data], 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().

Small discussion on the issue can be found here and in the std-discussion thread (which didn't get too much attention).

This requires a small change to std::basic_string's definition in 24.3.2 [basic.string] to add the method to std::basic_string, and another small change in [string.accessors] to define the new method.

[2015-02 Cologne]

Back to LEWG.


Marshall says: this issue has been resolved by P0272R1.

Proposed resolution:

This wording is relative to N3936.

  1. Change class template basic_string synopsis, 24.3.2 [basic.string], as indicated:

    namespace std {
      template<class charT, class traits = char_traits<charT>,
      class Allocator = allocator<charT> >
      class basic_string {
        // 21.4.7, string operations:
        const charT* c_str() const noexcept;
        const charT* data() const noexcept;
        charT* data() noexcept;
        allocator_type get_allocator() const noexcept;
  2. Add the following sequence of paragraphs following [string.accessors] p3, as indicated:

    charT* data() noexcept;

    -?- Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].

    -?- Complexity: Constant time.

    -?- Requires: The program shall not alter the value stored at p + size().