C++中一些知识点

定义与声明的区别

声明(Declaration)使得名字为程序所知,一个程序想使用在别处出现的名字就需要声明。
定义(Definition)产生与名字相关的实体,分配内存空间。

1
2
extern int a;    //仅声明
int b; //声明并定义

:这个是c++分离式编译的特性之一

显式访问全局变量

一旦在块作用域内有变量覆盖了全局变量,可以通过::操作符显式访问全局变量。

1
::reuse; //全局变量

引用

主要指左值引用。

1
2
int ival = 21;
int &refVal = ival; // 相当于给了变量别名,且引用定义时必须初始化

引用因为自己不是一个对象,所以没有引用的引用

指针相关操作符的多重意义

1
2
3
4
5
6
int i = 42;
int &r = i; // &随类型名出现,是声明的一部分,r是一个引用
int *p; // *随类型名出现,是声明的一部分,r是一个指针
p = &i; // &出现在表达式中,是一个取地址符
*p = i; // *出现在表达式中,是一个解引用符
int &r2 = *p; // &是声明引用,*是一个解引用符

注意定义时*最好和变量写一起

1
int *p1,*p2

可以有对指针的引用:

1
2
3
int i = 42;
int *p;
int *&r = p; //对指针的引用

(识别一大堆标识符时从右往左读,最近的产生最直接影响)

跨文件共享const

如果要跨文件共享const,定义和声明都需要加extern

指针和const

指向常量的指针和常量指针区别:

  • 指向常量的指针:指向一个常量,且自己认为指向的是常量,所以不允许对值修改
  • 常量指针(const pointer):指向位置不能变
    1
    2
    3
    4
    int errNum;
    int *const curError = &errNum; // const pointer
    const int test = 0;
    const int* cpt = &test; // pointer to const

new和malloc区别

new/delete

Allocate/release memory

  • Memory allocated from ‘Free Store’
  • Returns a fully typed pointer.
  • new (standard version) never returns a NULL (will throw on failure)
  • Are called with Type-ID (compiler calculates the size)
  • Has a version explicitly to handle arrays.
  • Reallocating (to get more space) not handled intuitively (because of copy constructor).
  • Whether they call malloc/free is implementation defined.
  • Can add a new memory allocator to deal with low memory (set_new_handler)
  • operator new/delete can be overridden legally
  • constructor/destructor used to initialize/destroy the object

malloc/free

Allocates/release memory

  • Memory allocated from ‘Heap’
  • Returns a void*
  • Returns NULL on failure
  • Must specify the size required in bytes.
  • Allocating array requires manual calculation of space.
  • Reallocating larger chunk of memory simple (No copy constructor to worry about)
  • They will NOT call new/delete
  • No way to splice user code into the allocation sequence to help with low memory.
  • malloc/free can NOT be overridden legally

表格:

1
2
3
4
5
6
7
8
9
10
11
12
 Feature                  | new/delete                     | malloc/free                   
--------------------------+--------------------------------+-------------------------------
Memory allocated from | 'Free Store' | 'Heap'
Returns | Fully typed pointer | void*
On failure | Throws (never returns NULL) | Returns NULL
Required size | Calculated by compiler | Must be specified in bytes
Handling arrays | Has an explicit version | Requires manual calculations
Reallocating | Not handled intuitively | Simple (no copy constructor)
Call of reverse | Implementation defined | No
Low memory cases | Can add a new memory allocator | Not handled by user code
Overridable | Yes | No
Use of (con-)/destructor | Yes | No