std::list<T,Allocator>::operator=

< cpp‎ | container‎ | list

list& operator=( const list& other );
(1)
(2)
list& operator=( list&& other );
(C++11 起)
(C++17 前)
list& operator=( list&& other ) noexcept(/* see below */);
(C++17 起)
list& operator=( std::initializer_list<T> ilist );
(3) (C++11 起)

替换容器内容。

1) 复制赋值运算符。以 other 的副本替换内容。std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::valuetrue ,则以源分配器的副本替换目标分配器。若源分配器与目标分配器不比较相等,则用目标( *this )分配器销毁内存,然后在复制元素前用 other 的分配器分配。 (C++11 起).、
2) 移动赋值运算符。用移动语义以 other 的内容替换内容(即从 other 移动 other 中的数据到此容器)。之后 other 在合法但未指定的状态。若 std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::valuetrue ,则用源分配器的副本替换目标分配器。若它为 false 且源与目标分配器不比较相等,则目标不能取走源内存的所有权,而必须单独移动赋值逐个元素,用自己的分配器按需分配额外的内存。任何情况下,原先在 *this 中的元素要么被销毁,要么以逐元素移动赋值替换。
3) 以 initializer_list ilist 所标识者替换内容。

参数

other - 用作数据源的另一容器
ilist - 用作数据源的 initializer_list

返回值

*this

复杂度

1)*thisother 的大小成线性。
2)*this 的大小成线性,除非分配器不比较相等且不传播,该情况下与 *thisother 的大小成线性。
3)*thisilist 的大小成线性。

异常

2)
noexcept 规定:  
noexcept(std::allocator_traits<Allocator>::is_always_equal::value)
(C++17 起)

注解

容器移动赋值(重载 (2) )后,除非不兼容的分配器强制逐元素赋值,否则指向 other 的引用、指针和迭代器(除了尾迭代器)都保持合法,不过指代的元素现在在 *this 中。当前标准通过 [container.requirements.general]/12 中的总括陈述保证这点,而 LWG 问题 2321 下正在考虑更直接的保证。

示例

下列代码用 operator= 赋值一个 std::list 给另一个:

#include <list>
#include <iostream>
 
void display_sizes(const std::list<int>& nums1,
                   const std::list<int>& nums2,
                   const std::list<int>& nums3)
{
    std::cout << "nums1: " << nums1.size() 
              << " nums2: " << nums2.size()
              << " nums3: " << nums3.size() << '\n';
}
 
int main()
{
    std::list<int> nums1 {3, 1, 4, 6, 5, 9};
    std::list<int> nums2; 
    std::list<int> nums3;
 
    std::cout << "Initially:\n";
    display_sizes(nums1, nums2, nums3);
 
    // 复制赋值从 nums1 复制数据到 nums2
    nums2 = nums1;
 
    std::cout << "After assigment:\n"; 
    display_sizes(nums1, nums2, nums3);
 
    // 移动赋值从 nums1 移动数据到 nums3,
    // 一同修改 nums1 和 nums3
    nums3 = std::move(nums1);
 
    std::cout << "After move assigment:\n"; 
    display_sizes(nums1, nums2, nums3);
}

输出:

Initially:
nums1: 6 nums2: 0 nums3: 0
After assigment:
nums1: 6 nums2: 6 nums3: 0
After move assigment:
nums1: 0 nums2: 6 nums3: 6

参阅

构造 list
(公开成员函数)
将值赋给容器
(公开成员函数)