Skip to content

Instantly share code, notes, and snippets.

@JeOam
Created June 14, 2018 10:23
Show Gist options
  • Save JeOam/f99f914046a373ec345c8175ffe3bb51 to your computer and use it in GitHub Desktop.
Save JeOam/f99f914046a373ec345c8175ffe3bb51 to your computer and use it in GitHub Desktop.
C++ Primer Notes
@JeOam
Copy link
Author

JeOam commented Jun 26, 2018

assert 是一种预处理宏。它使用一个表达式作为它的条件:

#include <cassert>
assert(expr);

首先对 expr 求值,如果表达式为假,assert 输出信息并终止程序的执行。如果表达式为真,assert 什么都不做。

assert 的行为依赖于一个名为 NDEBUG 的预处理变量的状态。如果定义了 NDEBUG,则 assert 什么都不做。默认状态下没有定义 NDEBUG,此时 assert 将执行运行时检测。我们可以使用一个 #define 语句定义 NDEBUG,从而关闭调试状态。

@JeOam
Copy link
Author

JeOam commented Jun 27, 2018

程序调试时的变量:

  • __func__: 输出当前调试的函数的名字
  • __FILE__: 存放文件名的字符串字面值
  • __LINE__: 存放当前行号的整型字面值
  • __TIME__: 存放文件编译时间的字符串字面值
  • __DATE__: 存放文件编译日期的字符串字面值

@JeOam
Copy link
Author

JeOam commented Jun 27, 2018

使用 classstruct 定义类的唯一区别就是默认的访问权限。

  • 定义在 public 说明符之后的成员在整个程序内可被访问,public 成员定义类的接口
  • 定义在 private 说明符之后的成员可以被类的成员函数访问,但是不能被使用该类的代码访问,private 部分封装了类的实现细节。

类可以允许其他类或函数访问它的非公有成员,方法是令其他类或者函数成为它的 友元friend)。如果类想把一个函数作为它的友元,只需要增加一条以 friend 关键词开始的函数声明语句即可。

@JeOam
Copy link
Author

JeOam commented Jun 28, 2018

一个 const 成员函数如果以引用的形式返回 *this,那么它的返回类型将是常量引用。

@JeOam
Copy link
Author

JeOam commented Jun 28, 2018

IO 对象无拷贝或赋值,进行 IO 操作的函数通用以引用的方式传递和返回流。

@JeOam
Copy link
Author

JeOam commented Jun 28, 2018

failbitbadbit 复位,但保持 eodbit 不变:

cin.clear(cin.rdstate() & ~cin.failbit & ~cin.badbit);
cout << unitbuf;  // 所以输出操作后,会立即刷新缓冲区,任何输出都立即刷新

cout << nounitbuf;  // 回到正常的缓冲方式

警告:如果程序崩溃,输出缓冲区不会被刷新。

@JeOam
Copy link
Author

JeOam commented Jul 5, 2018

@JeOam
Copy link
Author

JeOam commented Jul 13, 2018

一旦一个程序用光了它所有可用的内存,new 表达式就会失败。默认情况下,如果 new 不能分配所要求的内存空间,它会抛出一个类型为 bad_alloc 的异常。我们可以改变使用 new 的方式来阻止它抛出异常:

int *p1 = new int; // 如果分配失败,new  抛出 std::bad_alloc
int *p2 = new (nothrow) int; // 如果分配失败,new  返回一个空指针

bad_allocnothrow 都定义在头文件 new 中。

@JeOam
Copy link
Author

JeOam commented Jul 15, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment