Skip to content

Instantly share code, notes, and snippets.

@1000copy
Created August 1, 2022 03:23
Show Gist options
  • Save 1000copy/f6cb54994dee20bd38ae438de2860f23 to your computer and use it in GitHub Desktop.
Save 1000copy/f6cb54994dee20bd38ae438de2860f23 to your computer and use it in GitHub Desktop.
valueVSrefVSpointer.cpp
#include <iostream>
#include <assert.h>
void swap(int a, int b) {
int c = a;
a = b;
b = c;
assert(a == 1 && b == 0);
}
void swap_pointer(int* a, int* b) {
int c = *a;
*a = *b;
*b = c;
}
void swap_ref(int& a, int& b) {
int c = a;
a = b;
b = c;
}
int main(){
int a = 0;
int b = 1;
assert(a == 0 && b == 1);
swap(a, b);
assert(a == 0 && b == 1);
swap_pointer(&a, &b);
assert(a == 1 && b == 0);
swap_ref(a, b);
assert(a == 0 && b == 1);
}
//RECT rect;
//GetWindowRect(hwnd, &rect);
@1000copy
Copy link
Author

1000copy commented Aug 1, 2022

变量名实质上是一段连续内存空间的别名,程序中通过变量来申请并命名内存空间,通过变量的名字可以使用存储空间

对一段连续的内存空间只能取一个别名吗?

c++中新增了引用的概念,引用可以作为一个已定义变量的别名。

通过引用参数产生的效果同按地址传递是一样的。引用的语法更清楚简单:

  • 函数调用时传递的实参不必加“&”符
  • 在被调函数中不必在参数前加“*”符

当引用被用作函数参数的时,在函数内对任何引用的修改,将对还函数外的参数产生改变。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment