Próbuję zrozumieć, jak działa std :: ref.Jak działa reference_wrapper i 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
W powyższym kodzie, myślę, że parametr szablonu C
na trzecim wywołaniu funkcji jest tworzony jako std::reference_wrapper<int>
. Podczas czytania the reference, Zauważyłem, że nie ma operatora +=
w std::reference_wrapper<int>
. Zatem, jak ważna jest c += 1;
?
Następnie, c nadal jest plikiem referencyjnym, prawda? –
Sungmin
@Sungmin: Rzeczywiście sam 'c' nie może zmienić typu; ale '+ =' jest stosowane do wyniku 'c.operator int &()', który będzie odniesieniem do celu 'reference_wrapper'. –
Dziękuję, rozumiem. – Sungmin