您的位置:首页 > 编程语言 > C语言/C++

深入理解C++11 第二章兼容性稳定性 学习笔记

2016-08-19 11:54 281 查看
1 __func__预定义标识符
基本功能为返回所在函数的名字

我的VS2013上试了一下,发现C++环境中貌似需要用__FUNCTION_,结果一样

上代码

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

const char* hello(){
return __FUNCTION__; //__func__
}

const char* world(){
return __FUNCTION__;//__func__
}

int _tmain(int argc, _TCHAR* argv[])
{
std::cout << hello() << "," << world() << endl;

return 0;
}


函数输出 hello world

2 C++11 标准中定义了与#pragma功能相同的操作符_Pragma 其用法与sizeof等操作符一样
区别:_Pragma可以在宏中展开,而#pragma不可以,_Pragma用起来更加灵活

3 C99中得到变长参数宏定义 __VA_ARGS__

4 C++11整型引入 long long
  tips:要查看平台上long long类型大小可以去查看 <limit.h> 文件中的LLONG_MIN 和 LLONG_MAX

5 C++11规定,扩展的整型必须和标准的整型一样,有符号型和无符号型占用相同大小空间。

6 宏__cplusplus 判断是否为C++编译环境

7 断言 assert宏 运行时断言  可用 NDUBUG 禁用assert宏

#include "stdafx.h"
#include <cassert>

char *ArrayAlloc(int n) {
assert(n > 0);
return new char
;
}

int _tmain(int argc, _TCHAR* argv[])
{
char* a = ArrayAlloc(0);

return 0;
}


8 C++11 新引入的static_assert 编译期断言
 接收两个参数,第一个参数为断言表达式,第二个为编码者自定义的警告信息。 注:static_assert断言表达式的结果必须是在编译时期可以计算的表达式,即必须是常量表达式。

9 异常
C++11中不再使用 throw(...) {...}, 被新的noexcept异常声明取代
noexcept 表示其修饰的函数不会抛出异常,如果noxcept修饰的函数抛出了异常,编译期会直接调用std::terminate() 来终止程序运行。写法为:

void fun() noexcept;

void fun() noexcept(常量表达式);

示例代码:

#include "stdafx.h"
#include <iostream>
using namespace std;

void Throw(){
throw 1;
}

void NoBlockThrow(){
Throw();
}

void BlockThrow() noexcept {
Throw();
}

int _tmain(int argc, _TCHAR* argv[])
{
try {
Throw();
}
catch (...) {
cout << "Found Throw" << endl;
}

try {
NoBlockThrow();
}
catch (...) {
cout << " Throw is not blocked" << endl;
}

try {
BlockThrow();
}
catch (...) {
cout << "Found Throw 1" << endl;
}

return 0;
}


noexcept作为操作符时可用于template

template<class T> void fun() noexcept(noexcept (T())) {}

这里面的第二个noexcept为操作符,意义为 fun是否为一个noexcept函数将由T是否为一个noexcept函数决定。

10 非静态成员的sizeof

在C++11中,对非静态成员使用sizeof 是合法的。

11 扩展friend语法

在C++11中,声明一个类为另一个类的友元时,不再需要使用class关键字。
这使得为类模板声明友元成为可能。

12 C++11 新增using定义类型别名 作用与typedef一样。

13 final/override 控制

C++中有一个特点,就是基类声明为virtual的函数,之后的重载版本都不需要再声明该函数为virtual.(这条特性有利有弊啊)

override: 如果派生类在虚函数声明时使用了override描述符,那么该函数必须重载其基类中的同名函数,否则代码无法编译通过。(override用来做辅助检查工作的)

14模板函数的默认模板参数

在C++11中模板和函数一样,可以有默认参数了。

类模板在为多个默认参数指定默认值得时候需要“从右往左”,函数模板不需要。

15 外部模板

template<typename T>void  fun(T) {}

extern template void fun<int>(int);

C++11 引入此特性的目的是减轻编译器压力,减少冗余代码。

16 C++11中不再对局部和匿名类型做模板实参加限制。

在C/C++中,即使是匿名类型的声明,也需要独立的表达式语句。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: