std::deque<T,Allocator>::operator=
出自cppreference.com
| |
(1) | |
| (2) | (C++11 起) (C++17 前) |
|
| (C++17 起) | ||
| |
(3) | (C++11 起) |
替換容器內容。
1) 複製賦值運算符。以
other 內容的副本替換內容。
|
若 |
(C++11 起) |
2) 移動賦值運算符。用移動語義以
other 的內容替換內容(即從 other 移動 other 中的數據到此容器中)。之後 other 處於合法但未指定的狀態。 若
std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value 為 true,則用 other 的分配器的副本替換 *this 的分配器。若它為 false 且 *this 與 other 的分配器比較不相等,則 *this 不能接管 other 所擁有的內存的所有權且必須單獨地移動賦值每個元素,並用其自身的分配器按需分配額外內存。任何情況下,原屬於 *this 的元素要麼被銷毀,要麼被逐元素移動賦值所替換。3) 以 initializer_list
ilist 所標識者替換內容。參數
| other | - | 用作數據源的另一容器 |
| ilist | - | 用作數據源的 initializer_list |
返回值
*this
複雜度
1) 與
*this 和 other 的大小成線性。2) 與
*this 的大小成線性,除非分配器比較不相等且不傳播,該情況下與 *this 和 other 的大小成線性。3) 與
*this 和 ilist 的大小成線性。異常
|
1-3) 可能會拋出由實現定義的異常。
|
(C++17 前) |
|
1,3) 可能會拋出由實現定義的異常。
2) noexcept 說明:
noexcept(std::allocator_traits<Allocator>::is_always_equal::value) |
(C++17 起) |
註解
在容器移動賦值(重載 (2))後,除非不兼容的分配器強制逐元素移動賦值,指向 other 的引用及迭代器(除了尾迭代器)保持合法,但將指代現於 *this 中的元素。當前標準由 [container.requirements.general]/12 中的總括陳述作出此保證,而 LWG 問題 2321 正在考慮更嚴格的保證。
示例
以下代碼使用 operator= 從一個 std::deque 賦值給另一個:
運行此代碼
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <deque>
void print(auto const comment, auto const& container)
{
auto size = std::size(container);
std::cout << comment << "{ ";
for (auto const& element : container)
std::cout << element << (--size ? ", " : " ");
std::cout << "}\n";
}
int main()
{
std::deque<int> x{1, 2, 3}, y, z;
const auto w = {4, 5, 6, 7};
std::cout << "Initially:\n";
print("x = ", x);
print("y = ", y);
print("z = ", z);
std::cout << "Copy assignment copies data from x to y:\n";
y = x;
print("x = ", x);
print("y = ", y);
std::cout << "Move assignment moves data from x to z, modifying both x and z:\n";
z = std::move(x);
print("x = ", x);
print("z = ", z);
std::cout << "Assignment of initializer_list w to z:\n";
z = w;
print("w = ", w);
print("z = ", z);
}
輸出:
Initially:
x = { 1, 2, 3 }
y = { }
z = { }
Copy assignment copies data from x to y:
x = { 1, 2, 3 }
y = { 1, 2, 3 }
Move assignment moves data from x to z, modifying both x and z:
x = { }
z = { 1, 2, 3 }
Assignment of initializer_list w to z:
w = { 4, 5, 6, 7 }
z = { 4, 5, 6, 7 }
參閱
構造 deque (公開成員函數) | |
| 將值賦給容器 (公開成員函數) |