简体   繁体   English

std :: swap如何在构造函数,赋值运算符和析构函数方面起作用?

[英]How does std::swap work in terms of constructors, assignment operators, and destructors?

如果我有T aT b并调用std::swap(a, b) ,则调用的复制构造函数,赋值运算符和析构函数的顺序是什么?

If there is no specialisation for T , then the generic version will do something along the lines of 如果T没有专门化,那么通用版本将按照

{
    T t = std::move(a);  // move construction
    a = std::move(b);    // move assignment
    b = std::move(t);    // move assignment
}                        // destruction of t

Some types (such as containers) might have specialisations which will swap internal pointers etc., with no temporary object and no object assignment. 某些类型(例如容器)可能具有专门化,将交换内部指针等,而没有临时对象且没有对象分配。

There is no specific order that is "mandated", it would all depend on the implementation provided by the Standard Library being used. 没有“强制性”的特定命令,这完全取决于所使用的标准库提供的实现。

A C++03 variation of std::swap would be: std::swap C ++ 03变体为:

template<typename T>
void swap(T& a, T& b) {
    T temp(a); // copy
    a = b;     // assign
    b = temp;  // assign
}

A C++11 implementation would be: C ++ 11实现为:

template<typename T>
void swap(T& a, T& b) {
    T temp = std::move(a); // move copy or normal copy (moves if moveable)
    a = std::move(b);      // move or assign
    b = std::move(temp);   // move or assign
}

Several std containers etc. do specialise on swap because they can offer better or more efficient implementations; 几个std容器等确实专注于swap因为它们可以提供更好或更有效的实现。 custom types could do the same. 自定义类型可以做到这一点。 In these specialisations, even more variation could or would occur. 在这些专业领域,甚至可能还会发生更多变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM