std::inplace_vector<T,N>::operator=
来自cppreference.com
| |
(1) | (C++26 起) |
| |
(2) | (C++26 起) |
| |
(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 的大小成线性。异常
2)
noexcept 说明:
noexcept(N == 0 || (std::is_nothrow_move_assignable_v<T> && std::is_nothrow_move_constructible_v<T>))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("赋值 initializer_list {} 给 x:", l);
x = l; // 重载 (3)
std::println("x = {}", x);
std::println("用大小大于 N 的 initializer_list 的赋值抛出异常:");
try
{
x = {1, 2, 3, 4, 5}; // 当 (initializer list size == 5) > (capacity 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 = ["", ""]
赋值 initializer_list [4, 5, 6, 7] 给 x:
x = [4, 5, 6, 7]
用大小大于 N 的 initializer_list 的赋值抛出异常:
ex.what(): std::bad_alloc
参阅
构造 inplace_vector (公开成员函数) | |
| 将值赋给容器 (公开成员函数) |