20230308cpp_knowledge

Mar 8, 2023

CPP Knowledge

1. const int a = 10; 修改值

1
2
3
4
5
6
7
8
9
int main() {
const int b = 10;
int* c = (int*)&b;
*c = 20;
cout << "b ptr: " << &b << " b value: " << b << " c ptr: " << c << " c value: "<< *c;
int n = 30;
n = *c;
cout << " n value: " << n << endl;
}

答案是: b ptr: 0x7ffeefbff704 b value: 10 c ptr: 0x7ffeefbff704 c value: 20 n value: 20

  1. b确实没被修改
  2. b、c地址相同,但是打印出来尽然不同
  3. 被修改过的值有效,可被赋值

2. 类函数属性调用

1
2
3
4
5
6
typedef Lval&(Lval::*Lval_Func)(Lenv&, Lval&);
class Lval {
Lval_Func func;
Lval& buildin_op(Lenv&, Lval&);
};
Lval aval;

aval如何调用func? 正常来说只需要复制后,调用方法:

1
2
3
aval.func = &Lval::buildin_op;
Lval_Func funcptr = aval.func;
aval.*funcptr(env, otherval);

3. operator= 正确使用

1
2
3
4
5
6
7
class Lval {
Lval& operator=(const Lval&);
};
Lval& Lval::operator=(const Lval& a) {
...
return *this;
}

operator= 无法直接赋值,如: Lval a; Lval& b = a; 正确做法是:

1
2
3
Lval a;
Lval b;
a = b;

4. operator== 正确使用

1
2
3
4
5
6
7
class Lval {
bool operator==(const Lval&);
}
bool Lval::operator==(const Lval& a) {
...
return *this;
}

左右都为引用,正确使用如:

1
2
3
Lval* a = new Lval;
Lval* b = new Lval;
bool isEq = *a == *b;

5. std::vector v; v.push_back(3);

1
2
3
4
5
6
7
8
9
10
11
12
13
int main() {
std::vector<struct pollfd> poll_args;
while (true) {
for (Conn* conn : fd2conn) {
if (!conn) continue;
struct pollfd pfd = {};
pfd.fd = conn->fd;
pfd.events = (conn->state == STATE_REQ) ? POLLIN : POLLOUT;
pfd.events = pfd.events | POLLERR;
poll_args.push_back(pfd);
}
}
}

std::vector::push_back() creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*> instead of std::vector.