定义与声明的区别
声明(Declaration)使得名字为程序所知,一个程序想使用在别处出现的名字就需要声明。
定义(Definition)产生与名字相关的实体,分配内存空间。
1 | extern int a; //仅声明 |
注:这个是c++分离式编译的特性之一
显式访问全局变量
一旦在块作用域内有变量覆盖了全局变量,可以通过::
操作符显式访问全局变量。
1 | ::reuse; //全局变量 |
引用
主要指左值引用。
1 | int ival = 21; |
引用因为自己不是一个对象,所以没有引用的引用
指针相关操作符的多重意义
1 | int i = 42; |
注意定义时*
最好和变量写一起
1 | int *p1,*p2 |
可以有对指针的引用:
1 | int i = 42; |
(识别一大堆标识符时从右往左读,最近的产生最直接影响)
跨文件共享const
如果要跨文件共享const,定义和声明都需要加extern
。
指针和const
指向常量的指针和常量指针区别:
- 指向常量的指针:指向一个常量,且自己认为指向的是常量,所以不允许对值修改
- 常量指针(const pointer):指向位置不能变
1
2
3
4int 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 | Feature | new/delete | malloc/free |