我想了解std :: ref是如何工作的。reference_wrapper和std :: ref如何工作?
#include <functional>
#include <iostream>
template <class C>
void func(C c){
c += 1;
}
int main(){
int x{3};
std::cout << x << std::endl;
func(x);
std::cout << x << std::endl;
func(std::ref(x));
std::cout << x << std::endl;
}
Output : 3 3 4
在上面的代碼,我認爲第三函數調用模板參數C
被實例化std::reference_wrapper<int>
。 閱讀時the reference, 我注意到std::reference_wrapper<int>
中沒有+=
運算符。 那麼,c += 1;
如何有效?
然後,c仍然是reference_wrapper,對吧? –
Sungmin
2013-05-14 11:54:51
@Sungmin:的確,'c'本身不能改變類型;但'+ ='應用於'c.operator int&()'的結果,該結果將成爲'reference_wrapper'目標的引用。 – 2013-05-14 11:56:27
謝謝,我明白了。 – Sungmin 2013-05-14 11:59:00