std::inplace_vector<T,N>:: operator=
From cppreference.net
<
cpp
|
container
|
inplace vector
|
constexpr
inplace_vector
&
operator
=
(
const
inplace_vector
&
other
)
;
|
(1) | (自 C++26 起) |
|
constexpr
inplace_vector
&
operator
=
(
inplace_vector
&&
other
)
noexcept ( /* 见下文 */ ) ; |
(2) | (自 C++26 起) |
|
constexpr
inplace_vector
&
operator
=
(
std::
initializer_list
<
T
>
init
)
;
|
(3) | (自 C++26 起) |
替换
inplace_vector
的内容。
1)
复制赋值运算符
。若
std::
inplace_vector
<
T, N
>
具有
平凡析构函数
,且
std::
is_trivially_copy_constructible_v
<
T
>
&&
std::
is_trivially_copy_assignable_v
<
T
>
为
true
,则同时为
平凡复制赋值运算符
。将内容替换为
other
内容的副本。
2)
移动赋值运算符
。若
std::
inplace_vector
<
T, N
>
具有
平凡析构函数
,且
std::
is_trivially_move_constructible_v
<
T
>
&&
std::
is_trivially_move_assignable_v
<
T
>
为
true
,则同时为
平凡移动赋值运算符
。通过移动语义将内容替换为
other
的内容(即将
other
中的数据移动至此容器)。此后
other
处于有效但未指定的状态。
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
>
&&
示例
运行此代码
#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
(公开成员函数) |
|
|
为容器赋值
(公开成员函数) |