网络推广平台为企业做好服务优化营商环境
js 与 C++引用和指针的关系
js 中既有引用的影子, 也有指针的影子。
1、引用用法
这里相当于C++ 中的引用, b是a的引用, 修改b ,a也改变。
 var a = { 1: 1 }var b = a;a = null;b[2] = 2;console.error(b); // { 1: 1, 2: 2 }
 
2、指针用法
这里 a,b应该按照指针理解。
var a = undefined;var b = a;a = { 1: 1 }console.error(b); // undefined
 
C++ 中指针写法:
#include <iostream>int main()
{// 初始int c = 0;int* a = nullptr;int* b = a;// a赋值后a = &c;if (b == nullptr) {std::cout << "b is still nullptr" << std::endl;}return 0;
}
 
内存形式:
// 初始
| Address | Variable | Value (points to) |
| ------- | -------- | ---------------- |
| 0x1000  | a        | 0x0              |
| 0x1004  | b        | 0x0              |// a赋值后
| Address | Variable | Value (points to) |
| ------- | -------- | ---------------- |
| 0x1000  | a        | 0x2000           |
| 0x1004  | b        | 0x0              |
| 0x2000  | -        | 5                |
 
================ 结束==================
3、与js 类似写法的C++中引用写法
var a = undefined;var b = a;a = { 1: 1 }console.error(b); // undefined
 
#include <iostream>int main() {// 初始状态int a;int& b = a;// a赋值后a = 10;std::cout << "b: " << ref << std::endl; // 10return 0;
}
 
内存状态:
| Address | Variable | Value |
| ------- | -------- | ----- |
| 0x1000  | a (b)    | 未定义|   // 初始状态
| 0x1000  | a (b)    | 10    |   // a赋值后
