template <typename T>
void myswap(T a,T b)
{
T temp = a;
a = b;
b = temp;
}
int main()
{
int m(20),n(30);
myswap(ref(m),ref(n));
//m is still 20 and n is still 30
}
为什么 m 和 n 的值没有互换?将包装在 std::ref
中的值传递给 INCREMENT 函数会导致原始变量(调用 INCREMENT 函数的堆栈帧中的变量)中的值发生变化。或者,std::ref
的使用是否受到限制?
最佳答案
std::ref
(及其关联的 std::reference_wrapper
)是为标准库中非常具体的用例设计的工具,应该只用于那些;如果你想在自己的地方使用它,你必须详细了解它并尊重它的作用。
从根本上说,reference_wrapper
更接近指针而不是引用。所以在你的交换函数中替换一个指针,你会发现没有理由假设它实际上会交换:
void myswap(int* a, int* b)
{
int* temp = a;
a = b;
b = temp;
}
关于c++ - std::ref 和 swap 函数似乎不能很好地协同工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34224054/