std::basic_string<CharT,Traits,Allocator>::basic_string
(1) | ||
basic_string(); explicit basic_string( const Allocator& alloc ); |
(до C++17) | |
basic_string() noexcept(noexcept( Allocator() )) : basic_string( Allocator() ) {} |
(начиная с C++17) (до C++20) |
|
constexpr basic_string() noexcept(noexcept( Allocator() )) : basic_string( Allocator() ) {} |
(начиная с C++20) | |
(2) | ||
basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() ); |
(до C++20) | |
constexpr basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() ); |
(начиная с C++20) | |
(3) | ||
basic_string( const basic_string& other, size_type pos, const Allocator& alloc = Allocator() ); |
(до C++20) | |
constexpr basic_string( const basic_string& other, size_type pos, const Allocator& alloc = Allocator() ); |
(начиная с C++20) | |
constexpr basic_string( basic_string&& other, size_type pos, const Allocator& alloc = Allocator() ); |
(3) | (начиная с C++23) |
(3) | ||
basic_string( const basic_string& other, size_type pos, size_type count, |
(до C++20) | |
constexpr basic_string( const basic_string& other, size_type pos, size_type count, |
(начиная с C++20) | |
constexpr basic_string( basic_string&& other, size_type pos, size_type count, |
(3) | (начиная с C++23) |
(4) | ||
basic_string( const CharT* s, size_type count, const Allocator& alloc = Allocator() ); |
(до C++20) | |
constexpr basic_string( const CharT* s, size_type count, const Allocator& alloc = Allocator() ); |
(начиная с C++20) | |
(5) | ||
basic_string( const CharT* s, const Allocator& alloc = Allocator() ); |
(до C++20) | |
constexpr basic_string( const CharT* s, const Allocator& alloc = Allocator() ); |
(начиная с C++20) | |
(6) | ||
template< class InputIt > basic_string( InputIt first, InputIt last, |
(до C++20) | |
template< class InputIt > constexpr basic_string( InputIt first, InputIt last, |
(начиная с C++20) | |
(7) | ||
basic_string( const basic_string& other ); |
(до C++20) | |
constexpr basic_string( const basic_string& other ); |
(начиная с C++20) | |
(7) | ||
basic_string( const basic_string& other, const Allocator& alloc ); |
(начиная с C++11) (до C++20) |
|
constexpr basic_string( const basic_string& other, const Allocator& alloc ); |
(начиная с C++20) | |
(8) | ||
basic_string( basic_string&& other ) noexcept; |
(начиная с C++11) (до C++20) |
|
constexpr basic_string( basic_string&& other ) noexcept; |
(начиная с C++20) | |
(8) | ||
basic_string( basic_string&& other, const Allocator& alloc ); |
(начиная с C++11) (до C++20) |
|
constexpr basic_string( basic_string&& other, const Allocator& alloc ); |
(начиная с C++20) | |
(9) | ||
basic_string( std::initializer_list<CharT> ilist, const Allocator& alloc = Allocator() ); |
(начиная с C++11) (до C++20) |
|
constexpr basic_string( std::initializer_list<CharT> ilist, const Allocator& alloc = Allocator() ); |
(начиная с C++20) | |
(10) | ||
template< class StringViewLike > explicit basic_string( const StringViewLike& t, |
(начиная с C++17) (до C++20) |
|
template< class StringViewLike > constexpr explicit basic_string( const StringViewLike& t, |
(начиная с C++20) | |
(11) | ||
template< class StringViewLike > basic_string( const StringViewLike& t, size_type pos, size_type n, |
(начиная с C++17) (до C++20) |
|
template< class StringViewLike > constexpr basic_string( const StringViewLike& t, size_type pos, size_type n, |
(начиная с C++20) | |
basic_string( std::nullptr_t ) = delete; |
(12) | (начиная с C++23) |
template< container-compatible-range<CharT> R > constexpr basic_string( std::from_range_t, R&& rg, |
(13) | (начиная с C++23) |
Создаёт новую строку из различных источников данных и, при необходимости, с использованием предоставленного пользователем распределителя alloc.
Allocator
не может считаться аллокатором. (начиная с C++17)[
pos,
pos + count)
из other. Если count == npos, если count не указано или если запрошенная подстрока выходит за конец строки, результирующая подстрока будет [
pos,
other.size())
. Если other является ссылкой rvalue, она остаётся в допустимом, но неопределённом состоянии. (начиная с C++23)[
s,
s + count)
не является допустимым диапазоном.[
s,
s + Traits::length(s))
не является допустимым диапазоном (например, если s нулевой указатель). Этот конструктор не используется для вывода аргументов шаблонного класса, если выводимый тип Allocator
не может считаться аллокатором. (начиная с C++17)[
first,
last)
.
Если |
(до C++11) |
Этот конструктор участвует в разрешении перегрузки, только если |
(начиная с C++11) |
std::basic_string_view<CharT, Traits>> равно true и std::is_convertible_v<const StringViewLike&, const CharT*> равно false.
[
pos,
pos + n)
из sv, как будто с помощью basic_string(sv.substr(pos, n), alloc).std::basic_string_view<CharT, Traits>> равно true.
std::basic_string
не может быть создан из nullptr.Содержание |
[править] Параметры
alloc | — | аллокатор, который будет использоваться для всех выделений памяти этой строки |
count | — | размер результирующей строки |
ch | — | значение для инициализации строки |
pos | — | позиция первого символа, который будет включен |
first, last | — | диапазон для копирования символов |
s | — | указатель на массив символов, который будет использоваться в качестве источника для инициализации строки |
other | — | другая строка, которая будет использоваться в качестве источника для инициализации строки |
ilist | — | std::initializer_list для инициализации строки |
t | — | объект (конвертируемый в std::basic_string_view) для инициализации строки |
rg | — | no section name |
[править] Сложность
[править] Исключения
Генерирует std::length_error, если длина создаваемой строки превышает max_size() (например, если count > max_size() для (2)). Вызовы Allocator::allocate
могут генерировать исключение.
Если по какой-либо причине генерируется исключение, эта функция не имеет эффекта (строгая гарантия безопасности исключений).
[править] Примечание
Инициализация строковым литералом, содержащим встроенные символы '\0', использует перегрузку (5), которая останавливается на первом нулевом символе. Этого можно избежать, указав другой конструктор или используя operator""s
:
std::string s1 = "ab\0\0cd"; // s1 содержит "ab" std::string s2{"ab\0\0cd", 6}; // s2 содержит "ab\0\0cd" std::string s3 = "ab\0\0cd"s; // s3 содержит "ab\0\0cd"
Макрос Тестирования функциональности | Значение | Стандарт | Функциональность |
---|---|---|---|
__cpp_lib_containers_ranges |
202202L | (C++23) | Конструктор с тегами (13) для создания no section name |
[править] Пример
#include <cassert> #include <cctype> #include <iomanip> #include <iostream> #include <iterator> #include <string> int main() { std::cout << "1) string(); "; std::string s1; assert(s1.empty() && (s1.length() == 0) && (s1.size() == 0)); std::cout << "s1.capacity(): " << s1.capacity() << '\n'; // не указано std::cout << "2) string(size_type count, CharT ch): "; std::string s2(4, '='); std::cout << std::quoted(s2) << '\n'; // "====" std::cout << "3) string(const string& other, size_type pos, size_type count): "; std::string const other3("Образец"); std::string s3(other3, 0, other3.length() - 1); std::cout << std::quoted(s3) << '\n'; // "Образец" std::cout << "4) string(const string& other, size_type pos): "; std::string const other4("Mutatis Mutandis"); std::string s4(other4, 8); std::cout << std::quoted(s4) << '\n'; // "Mutandis", то есть [8, 16) std::cout << "5) string(CharT const* s, size_type count): "; std::string s5("C-style", 7); std::cout << std::quoted(s5) << '\n'; // "C-style", то есть [0, 7) std::cout << "6) string(CharT const* s): "; std::string s6("строка\0в стиле С"); std::cout << std::quoted(s6) << '\n'; // "строка" std::cout << "7) string(InputIt first, InputIt last): "; char mutable_c_str[] = "another C-style string"; std::string s7(std::begin(mutable_c_str) + 8, std::end(mutable_c_str) - 1); std::cout << std::quoted(s7) << '\n'; // "другая строка в стиле C" std::cout << "8) string(string&): "; std::string const other8("Образец"); std::string s8(other8); std::cout << std::quoted(s8) << '\n'; // "Образец" std::cout << "9) string(string&&): "; std::string s9(std::string("С++ на ") + std::string("примере")); std::cout << std::quoted(s9) << '\n'; // "С++ на примере" std::cout << "a) string(std::initializer_list<CharT>): "; std::string sa({'C', '-', 's', 't', 'y', 'l', 'e'}); std::cout << std::quoted(sa) << '\n'; // "C-style" // до C++11 разрешение перегрузки выбирает string(InputIt first, InputIt last) // [с InputIt = int], которая ведёт себя *как если бы* // string(size_type count, CharT ch). // После C++11 конструктор InputIt отключен для целочисленных типов и вызывается: std::cout << "b) string(size_type count, CharT ch) вызвана: "; std::string sb(3, std::toupper('a')); std::cout << std::quoted(sb) << '\n'; // "AAA" // std::string sc(nullptr); // До C++23: генерирует std::logic_error // Начиная с C++23: не компилируется, // смотрите перегрузку (12) // std::string sc(0); // То же, что и выше, поскольку литерал 0 является // константой нулевого указателя auto const range = {0x43, 43, 43}; #ifdef __cpp_lib_containers_ranges std::string sc(std::from_range, range); // тегированный конструктор (13) std::cout << "c) string(std::from_range, range) вызвана: "; #else std::string sc(range.begin(), range.end()); // возврат к перегрузке (7) std::cout << "c) string(range.begin(), range.end()) вызвана: "; #endif std::cout << std::quoted(sc) << '\n'; // "C++" }
Возможный вывод:
1) string(); s1.capacity(): 15 2) string(size_type count, CharT ch): "====" 3) string(const string& other, size_type pos, size_type count): "Образец" 4) string(const string& other, size_type pos): "Mutandis" 5) string(CharT const* s, size_type count): "C-style" 6) string(CharT const* s): "строка" 7) string(InputIt first, InputIt last): "C-style string" 8) string(string&): "Образец" 9) string(string&&): "С++ на примере" a) string(std::initializer_list<CharT>): "C-style" b) string(size_type count, CharT ch) вызвана: "AAA" c) string(std::from_range, range) вызвана: "C++"
[править] Отчёты о дефектах
Следующие изменения поведения были применены с обратной силой к ранее опубликованным стандартам C++:
Номер | Применён | Поведение в стандарте | Корректное поведение |
---|---|---|---|
LWG 301 | C++98 | перегрузка (6) не использовала параметр alloc, еслиInputIt являлся целочисленным типом
|
использует этот параметр |
LWG 847 | C++98 | не было никаких гарантий безопасности исключений | добавлена надёжная гарантия безопасности исключений |
LWG 2193 | C++11 | конструктор по умолчанию является явным | сделан неявным |
LWG 2583 | C++98 | нет возможности предоставить аллокатор дляbasic_string(str, pos)
|
существует конструктор basic_string(str, pos, alloc)
|
LWG 2946 | C++17 | перегрузка (10) в некоторых случаях вызывает неоднозначность |
исправлено, сделав её шаблоном |
LWG 3076 | C++17 | два конструктора могут вызвать неоднозначность при выводе аргументов шаблонного класса |
ограничено |
[править] See also
присваивает символы строке (public функция-элемент) | |
присваивает значения строке (public функция-элемент) | |
(C++11) |
преобразует целое значение или значение с плавающей запятой в string (функция) |
(C++11) |
преобразует целое значение или значение с плавающей запятой в wstring (функция) |
(C++17) |
конструирует basic_string_view (public функция-элемент std::basic_string_view<CharT,Traits> )
|