我致力于重新实现 C++ STL 库中的一些方法。还有一个关于通用交换实现的问题:我是否应该使用 const
修饰符作为临时变量?
这是我的变体:
template<typename T>
void swap(T& a, T& b)
{
const T tmp = a;
a = b;
b = tmp;
}
更新:
我检查了几个STL实现;有些使用 const,而另一些则没有。
我认为,使用 const 可能会限制交换
的通用性...
我想编写可移植的实现,并且这是最通用的(接受大多数类)。
最佳答案
这就是你应该这样做的方式,也是为什么 tmp 不应该是 const 的原因:
template<typename T>
void swap(T& a, T& b)
{
T tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);//needs to change tmp, so tmp cannot be const
}
这允许对 tmp 进行移动分配(如果可能)。
但是,这还有很多细微差别。
关于c++ - 重新实现 std::swap,我应该使用 const 作为 tmp 变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17753743/