Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::basic_string::data — buffer access and write bounds

Pair `data()` with `size()` to preserve embedded zeros, and check the string’s bounds and lifetime before using the pointer.

Version: ISO C++23; implementation support may vary

Syntax

// <string>; members of std::basic_string<CharT, Traits, Allocator> in C++23
constexpr const CharT* data() const noexcept;
constexpr CharT* data() noexcept;

std::basic_string::data, declared in <string>, returns a pointer to the string’s contiguous storage in constant time, without copying or transferring ownership. A const string selects the const CharT* overload; a non-const string selects the CharT* overload, added in C++17. Since C++11, the const overload has been noexcept and the buffer has been guaranteed to be null-terminated. The writable overload has been noexcept since its introduction; both overloads have been constexpr since C++20. This entry describes ISO C++23; implementation support may vary.

The string’s elements occupy [s.data(), s.data() + s.size()). The element at s.data()[s.size()] is CharT{} and is not counted by size(); for an empty string, the pointer points to that terminator. c_str() gives read-only access to the same buffer. A C-string function such as std::strlen for char stops at the first zero, even if it’s embedded in the string. std::basic_string_view::data() does not guarantee a terminator at the end of the view.

For an exact copy, pass a pointer and an element count, as in std::string(s.data(), s.size()) for a std::string. For a slice starting at pos, check pos <= s.size() before checking count <= s.size() - pos. size() counts CharT elements, not Unicode characters: std::string uses char, while std::u8string (since C++20) uses char8_t, so its pointer cannot be passed directly to an API expecting const char*.

Do not write through the pointer from the const overload. Through CharT*, overwrite only elements with indices less than size(). Setting the terminator to a nonzero value or accessing beyond it through this pointer is undefined behavior. reserve() does not increase size(); to make a larger writable range, call resize() and then get a fresh pointer. Do not use it after the string is destroyed, including a temporary string, or after an operation that may invalidate it, such as append().

Examples

#include <cstring>
#include <iostream>
#include <string>

int main() {
    const std::string input("A\0B", 3);
    std::string copy(input.data(), input.size());
    copy.data()[2] = 'C';

    std::cout << copy.size() << '\n'
              << std::strlen(copy.c_str()) << '\n'
              << copy.data()[2] << '\n';
}

Result

3
1
C

The counted constructor preserves the embedded zero. Writing through `data()` changes the third element to `C`, while `std::strlen` still returns `1`.

Related lessons

  • C++ · Lesson 49 · Advanced · Version: 3
  • C++ · Lesson 58 · Advanced · Version: 3

Sources