Namespaces
Variants

std::operator+(std::basic_string)

De es.cppreference.net
 
 
 
std::basic_string
 
Definido en el encabezado <string>
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( const std::basic_string<CharT,Traits,Alloc>& lhs,
               const std::basic_string<CharT,Traits,Alloc>& rhs );
(1) (constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( const std::basic_string<CharT,Traits,Alloc>& lhs,
               const CharT* rhs );
(2) (constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( const std::basic_string<CharT,Traits,Alloc>& lhs,
               CharT rhs );
(3) (constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
constexpr std::basic_string<CharT,Traits,Alloc>
    operator+( const std::basic_string<CharT,Traits,Alloc>& lhs,
               std::type_identity_t<std::basic_string_view<CharT,Traits>> rhs );
(4) (desde C++26)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( const CharT* lhs,
               const std::basic_string<CharT,Traits,Alloc>& rhs );
(5) (constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( CharT lhs,
               const std::basic_string<CharT,Traits,Alloc>& rhs );
(6) (constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
constexpr std::basic_string<CharT,Traits,Alloc>
    operator+( std::type_identity_t<std::basic_string_view<CharT,Traits>> lhs,
               const std::basic_string<CharT,Traits,Alloc>& rhs );
(7) (desde C++26)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( std::basic_string<CharT,Traits,Alloc>&& lhs,
               std::basic_string<CharT,Traits,Alloc>&& rhs );
(8) (desde C++11)
(constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( std::basic_string<CharT,Traits,Alloc>&& lhs,
               const std::basic_string<CharT,Traits,Alloc>& rhs );
(9) (desde C++11)
(constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( std::basic_string<CharT,Traits,Alloc>&& lhs,
               const CharT* rhs );
(10) (desde C++11)
(constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( std::basic_string<CharT,Traits,Alloc>&& lhs,
               CharT rhs );
(11) (desde C++11)
(constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
constexpr std::basic_string<CharT,Traits,Alloc>
    operator+( std::basic_string<CharT,Traits,Alloc>&& lhs,
               std::type_identity_t<std::basic_string_view<CharT,Traits>> rhs );
(12) (desde C++26)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( const std::basic_string<CharT,Traits,Alloc>& lhs,
               std::basic_string<CharT,Traits,Alloc>&& rhs );
(13) (desde C++11)
(constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( const CharT* lhs,
               std::basic_string<CharT,Traits,Alloc>&& rhs );
(14) (desde C++11)
(constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
std::basic_string<CharT,Traits,Alloc>
    operator+( CharT lhs,
               std::basic_string<CharT,Traits,Alloc>&& rhs );
(15) (desde C++11)
(constexpr desde C++20)
template< class CharT, class Traits, class Alloc >
constexpr std::basic_string<CharT,Traits,Alloc>
    operator+( std::type_identity_t<std::basic_string_view<CharT,Traits>> lhs,
               std::basic_string<CharT,Traits,Alloc>&& rhs );
(16) (desde C++26)

Devuelve una cadena que contiene caracteres de lhs seguidos de los caracteres de rhs. Equivalente a:

1,2) std::basic_string<CharT, Traits, Allocator> r = lhs; r.append(rhs); return r;
3) std::basic_string<CharT, Traits, Allocator> r = lhs; r.push_back(rhs); return r;
4) std::basic_string<CharT, Traits, Allocator> r = lhs; r.append(rhs); return r;
5) std::basic_string<CharT, Traits, Allocator> r = rhs; r.insert(0, lhs); return r;
6) std::basic_string<CharT, Traits, Allocator> r = rhs; r.insert(r.begin(), lhs); return r;
7) std::basic_string<CharT, Traits, Allocator> r = rhs; r.insert(0, lhs); return r;
8) lhs.append(rhs); return std::move(lhs); excepto que tanto lhs como rhs se dejan en estados válidos pero no especificados. Si lhs y rhs tienen asignadores iguales, la implementación puede mover desde cualquiera.
9,10) lhs.append(rhs); return std::move(lhs);
11) lhs.push_back(rhs); return std::move(lhs);
12) lhs.append(rhs); return std::move(lhs);
13,14) rhs.insert(0, lhs); return std::move(rhs);
15) rhs.insert(rhs.begin(), lhs); return std::move(rhs);
16) rhs.insert(0, lhs); return std::move(rhs);

El asignador utilizado para el resultado es:

1-4) std::allocator_traits<Alloc>::select_on_container_copy_construction(lhs.get_allocator())
5-7) std::allocator_traits<Alloc>::select_on_container_copy_construction(rhs.get_allocator())
8-12) lhs.get_allocator()
13-16) rhs.get_allocator()

En otras palabras:

  • Si un operando es un basic_string rvalue, se utiliza su asignador.
  • De lo contrario, select_on_container_copy_construction se utiliza en el asignador del operando basic_string lvalue.

En cada caso, se prefiere el operando izquierdo cuando ambos son basic_strings de la misma categoría de valor.

Para (8-16), todos los operandos basic_string rvalue se dejan en estados válidos pero no especificados.

(desde C++11)

Parámetros

lhs - string , string view (since C++26) , carácter, o puntero al primer carácter en un arreglo terminado en nulo
rhs - string , string view (since C++26) , carácter, o puntero al primer carácter en un arreglo terminado en nulo

Valor de retorno

Una cadena que contiene los caracteres de lhs seguidos por los caracteres de rhs , utilizando el asignador determinado como se indicó anteriormente (since C++11) .

Notas

operator+ debe usarse con gran precaución cuando hay asignadores con estado involucrados (como cuando se usa std::pmr::string ) (desde C++17) . Antes de P1165R1 , el asignador utilizado para el resultado se determinaba por accidentes históricos y podía variar de una sobrecarga a otra sin razón aparente. Además, para ( 1-5 ) , el comportamiento de propagación del asignador varía entre las principales implementaciones de bibliotecas estándar y difiere del comportamiento descrito en el estándar.

Debido a que el asignador utilizado por el resultado de operator+ es sensible a la categoría de valor, operator+ no es asociativo con respecto a la propagación del asignador:

using my_string = std::basic_string<char, std::char_traits<char>, my_allocator<char>>;
my_string cat();
const my_string& dog();
my_string meow = /* ... */, woof = /* ... */;
meow + cat() + /* ... */; // usa select_on_container_copy_construction en el asignador de meow
woof + dog() + /* ... */; // usa el asignador del valor de retorno de dog() en su lugar
meow + woof + meow; // usa select_on_container_copy_construction en el asignador de meow
meow + (woof + meow); // usa SOCCC en el asignador de woof en su lugar

Para una cadena de invocaciones de operator+ , el asignador utilizado para el resultado final puede controlarse anteponiendo un basic_string valor-r con el asignador deseado:

// usar my_favorite_allocator para el resultado final
my_string(my_favorite_allocator) + meow + woof + cat() + dog();

Para un control mejor y portable sobre los asignadores, se deben usar funciones miembro como append , insert , y operator+= en una cadena resultado construida con el asignador deseado.

(desde C++11)

El uso de std:: type_identity_t como parámetro en las sobrecargas ( 4 ) , ( 7 ) , ( 12 ) , y ( 16 ) asegura que un objeto de tipo std:: basic_string < CharT, Traits, Allocator > siempre pueda concatenarse con un objeto de tipo T con conversión implícita a std:: basic_string_view < CharT, Traits > , y viceversa, según las reglas de resolución de sobrecarga .

Macro de prueba de características Valor Std Característica
__cpp_lib_string_view 202403 (C++26) Concatenación de strings y string views, sobrecargas ( 4 ) , ( 7 ) , ( 12 ) , ( 16 )
(desde C++26)

Ejemplo

#include <iostream>
#include <string>
#include <string_view>
int main()
{
    std::string s1 = "Hello";
    std::string s2 = "world";
    const char* end = "!\n";
    std::cout << s1 + ' ' + s2 + end;
    std::string_view water{" Water"};
    #if __cpp_lib_string_view >= 202403
    std::cout << s1 + water + s2 << end; // overload (4), then (1)
    #else
    std::cout << s1 + std::string(water) + s2 << end; // OK, but less efficient
    #endif
}

Salida:

Hello world!
Hello Waterworld!

Informes de defectos

Los siguientes informes de defectos que modifican el comportamiento se aplicaron retroactivamente a los estándares publicados anteriormente de C++.

DR Applied to Behavior as published Correct behavior
P1165R1 C++11 la propagación del asignador de memoria es irregular e inconsistente se hizo más consistente

Véase también

agrega caracteres al final
(función miembro pública)
agrega caracteres al final
(función miembro pública)
inserta caracteres
(función miembro pública)