Question #174
According to the C++17 standard, what is the output of this program?
#include<iostream>
void f(int& a, const int& b) {
std::cout << b;
a = 1;
std::cout << b;
}
int main(){
int x = 0;
f(x,x);
}
01
b是一个const引用,我们不能修改它,但是不能保证它不会被其他地方修改,a也是x的别名,所以可以通过a修改x使b中的值改变。
#include <iostream>
void f(float) { std::cout << 1; }
void f(double) { std::cout << 2; }
int main() {
f(2.5);
f(2.5f);
}
21
emmm...过。
Question #116
#include <iostream>
#include <utility>
int y(int &) { return 1; }
int y(int &&) { return 2; }
template <class T> int f(T &&x) { return y(x); }
template <class T> int g(T &&x) { return y(std::move(x)); }
template <class T> int h(T &&x) { return y(std::forward<T>(x)); }
int main() {
int i = 10;
std::cout << f(i) << f(20);
std::cout << g(i) << g(20);
std::cout << h(i) << h(20);
return 0;
}
112212
T&&看起来像右值引用但是在函数模板中它其实是通用引用,它取决于用于实例化模板的类型。如果使用左值实例化,它会折叠成左值引用;如果使用右值实例化,它会折叠成右值引用。
对于f函数,虽然参数20是右值,但是x始终是左值(尽管它本身是右值引用),所以无论是传入i还是20都会匹配到y(int &),g函数中move(x)会得到右值引用,所以两次都调用了y(int &&),std::forward(x)会保留原数据类型,i是左值,20是右值,所以输出12。
评论 (0)