gpt4 book ai didi

c++ - 右值引用、复制和移动

转载 作者:行者123 更新时间:2023-12-01 14:47:10 25 4
gpt4 key购买 nike

考虑以下用于 swap 的代码部分:

//for some type T
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
下面这个:
//for some type T
void swap(T& a, T& b) {
T temp = static_cast<T&&>(a);
a = static_cast<T&&>(b);
b = static_cast<T&&>(temp);
}
我有以下疑问:
它们之间有什么区别?我的意思是为什么第一个交换比第二个更贵?
引用:C++编程语言7.7.2

最佳答案

What is the difference between them? I mean why the first swap is more expensive than the second one ?


第二个为支持它的类型启用移动(即具有移动赋值运算符)。这些类型包括标准 vector 、字符串等。
对于不支持移动语义的基本类型(int、bool 等),没有区别,都是普通的拷贝。

关于c++ - 右值引用、复制和移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63259165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com