cpp-note

2016-08-10

  • 以下的代码编译器是支持的
1
2
3
4
int func(int * ){
print("hello");
return 0;
}

2016-08-11

  • 注意以下例子, ::a表示的是全局变量a。
1
2
3
4
5
6
7
8
9
10
11
#include <new>
#include <iostream>

using namespace std;
int a = 5;

int main() {
int a = 3;
cout << a << " " << ::a << endl;
return 0;
}

2016-08-15

  • new (int (*[10])()); // okay: allocates an array of 10 pointers to functions
  • new int(*[10])(); // error: parsed as (new int) (*[10]) ()
  • 关于函数指针,其关键在于把*写在了括号里面。看下面的例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
void func(int a){
cout << a << endl;
}
void (* p_f)(int);
void (* p_f_array[2])(int);
int main() {
p_f = func; // ok
p_f(3);
p_f = &func; // ok too!
p_f(4);
p_f_array[0] = func;
p_f_array[1] = p_f;
p_f_array[0](0);
p_f_array[1](1);
return 0;
}
  • 关于expression new: (optional) new (placement_params)(optional) ( type ) initializer(optional)(optional) new (placement_params)(optional) type initializer(optional), 如果表达式中不包含placement_params的话,编译器会首先分配相应内存空间(可能会调用operation new来分配内存空间)。如果带placement_params的话,将不会再分配内存了。文档里是这么说的“If placement_params are provided, they are passed to the allocation function as additional arguments. Such allocation functions are known as “placement new”, after the standard allocation function void operator new(std::size_t, void), which simply returns its second argument unchanged. This is used to construct objects in allocated storage:”
1
2
3
4
char* ptr = new char[sizeof(T)]; // allocate memory
T* tptr = new(ptr) T; // construct in allocated storage ("place")
tptr->~T(); // destruct
delete[] ptr; // deallocate memory