Namespaces
Variants

std::inplace_vector<T,N>::operator=

来自 zh.cppreference.net
 
 
 
 
constexpr inplace_vector& operator=( const inplace_vector& other );
(1) (C++26 起)
constexpr inplace_vector& operator=( inplace_vector&& other )
    noexcept(/* see below */);
(2) (C++26 起)
constexpr inplace_vector& operator=( std::initializer_list<T> init );
(3) (C++26 起)

替换 inplace_vector 的内容。

1) 复制赋值运算符。以 other 内容的副本替换内容。
此运算符是平凡的,如果 std::inplace_vector<T, N> 具有平凡的析构函数,且 std::is_trivially_copy_constructible_v<T> && std::is_trivially_copy_assignable_v<T> 是 true。
2) 移动赋值运算符。以移动语义替换为 other 的内容(即 other 中的数据被从 other 移动到该容器中)。此后 other 处于有效但未指定的状态。
此运算符是平凡的,如果 std::inplace_vector<T, N> 具有平凡的析构函数,且 std::is_trivially_move_constructible_v<T> && std::is_trivially_move_assignable_v<T> 是 true。
3) 替换为初始化器列表 init 所标识的内容。

参数

other - 用于初始化容器元素的另一个 inplace_vector 源对象
init - 用于初始化容器元素的初始化列表

复杂度

1,2) 与 * this 和 other 的大小成线性关系。
3) 与 * this 及 init 的大小呈线性关系。

异常

3) 当 init. size ( ) > N 时抛出 std::bad_alloc 。

示例

#include <initializer_list>
#include <inplace_vector>
#include <new>
#include <print>
#include <ranges>
#include <string>
int main()
{
    std::inplace_vector<int, 4> x({1, 2, 3}), y;
    std::println("初始状态:");
    std::println("x = {}", x);
    std::println("y = {}", y);
    std::println("复制赋值将数据从 x 复制到 y:");
    y = x; // 重载 (1)
    std::println("x = {}", x);
    std::println("y = {}", y);
    std::inplace_vector<std::string, 3> z, w{"\N{CAT}", "\N{GREEN HEART}"};
    std::println("初始状态:");
    std::println("z = {}", z);
    std::println("w = {}", w);
    std::println("移动赋值将数据从 w 移动到 z:");
    z = std::move(w); // 重载 (2)
    std::println("z = {}", z);
    std::println("w = {}", w); // w 处于有效但未指定状态
    auto l = {4, 5, 6, 7};
    std::println("将初始化列表 {} 赋值给 x:", l);
    x = l; // 重载 (3)
    std::println("x = {}", x);
    std::println("当初始化列表大小超过 N 时赋值会抛出异常:");
    try
    {
        x = {1, 2, 3, 4, 5}; // 抛出异常:(初始化列表大小 == 5) > (容量 N == 4)
    }
    catch(const std::bad_alloc& ex)
    {
        std::println("ex.what(): {}", ex.what());
    }
}

可能的输出:

初始状态:
x = [1, 2, 3]
y = []
复制赋值将数据从 x 复制到 y:
x = [1, 2, 3]
y = [1, 2, 3]
初始状态:
z = []
w = ["🐈", "💚"]
移动赋值将数据从 w 移动到 z:
z = ["🐈", "💚"]
w = ["", ""]
将初始化列表 [4, 5, 6, 7] 赋值给 x:
x = [4, 5, 6, 7]
当初始化列表大小超过 N 时赋值会抛出异常:
ex.what(): std::bad_alloc

另请参阅

构造 inplace_vector
(公开成员函数)
为容器赋值
(公开成员函数)