PPPUC++ Reading Note
Table of Contents
1 CH. 17 Memory, Address
int main() { char a = 'a'; char b = 'b'; void *pv = &a; int *pa = (int*)pv; std:: cout <<*pa<<std::endl; *pa = 65535; std:: cout <<(char*)&a<<" "<<(char*)&b<<std::endl; std:: cout <<a<<" "<<b<<std::endl; return 0; } �� b�� � b
实测堆上分配的内存并没有溢出
int* 和 char* 不能直接互相赋值的原因: 索引数组时地址跨越长度
1.1 初始化:
为了避免误用未初始化的变量, 尽量保证变量在被声明的同时初始化.
1.2 空指针:
c++11 引入了nullptr, 旨在于解决null的二义性问题
1.3 Free-Store:
Free-Store由Store Manager管理
1.4 析构函数:
占用Free-Store的类都需要析构函数
1.5 指针和引用:
传值和传指针: 指针允许nullptr, 可能需要额外写防御代码.
2 CH. 18 Vector and Array
- initializerlist
- copy constructor
- copy assignment
2.1 Copying
2.2 Moving
&& ?
2.3 explicit
2.4 Get & Set
索引靠重载[]运算符实现, 并返回reference.
- 若返回值则只能get无法set(可用作const版本), 返回指针则书写起来比较别扭.
2.5 Array
array的问题: 编译器难以做到边界检查 pointer arithmetic
2.6 Excrise
/ / main.cpp / PPPUC / / Created by Tsubasa on 1/30/16. / Copyright (c) 2016 tsu. All rights reserved. //
#include <iostream> using namespace std;
class Vector { int sz; double * elem; public: Vector(int s): sz{s}, elem{new double[s]} { for(int i = 0; i < sz; i++) elem[i] = 0; }
Vector(initializerlist<double> lst): sz{(int)lst.size()},elem{new double[lst.size()]} { copy(lst.begin(),lst.end(),elem); }
Vector(const Vector&);
Vector& operator=(const Vector&);
~Vector(){delete[] elem;} void Set(int, double); void Print(); };
void Vector::Set(int index, double value) { if (index >= sz) return; elem[index] = value; }
void Vector::Print() { for (int i = 0; i < sz; i++) { cout<<(elem[i])<<endl; } }
Vector::Vector(const Vector& arg) :sz(arg.sz),elem(new double[arg.sz]) { copy(arg.elem,arg.elem+arg.sz,elem); }
Vector& Vector::operator=(const Vector& arg) { double *d = new double[arg.sz]; copy(arg.elem,arg.elem+arg.sz,d); delete[] elem; elem = d; sz = arg.sz; return *this; }
// exc 1 char strup(const char a) { int sz = 0; while ( a[sz] != 0 ) sz++;
char * res = new char[sz+1]; for(int i = 0; i <= sz; i++) res[i] = *a+i;
return res; }
// exc 2
int main(int argc, const char * argv[]) {
return 0; }