[2018年5月3号]C++ primer 课后练习 第十二章 动态内存

xiaoxiao2021-02-28  19

12.16

12.17

a.不合法 ix是一个整形,不能给unique_pt<int> 作为初始参数

b.不合法,IDE不会报错,但是pi不是一块动态内存,在退出p1作用域时候,会释放pi导致报错

c.正确

d不合法,同b

e.正确

f.不合法,但是IDE不错报错,p5和p2指向同一块内存,当退出p5作用域时候,p2的指针会称为空悬指针,再退出p2作用域,p2会再次删除指向的内存,导致程序无法继续执行

12.18

shared_ptr可能有多个指针同时指向同一块内存,假设存在release函数并执行,当前指针会放弃对该片内存的控制,但其他所有指向那块内存的指针会称为空悬指针

12.19

class StrBlobPtr { public: StrBlobPtr():curr(0){} StrBlobPtr(StrBlob& a, size_t sz = 0):wptr(a.data),curr(sz){} string& deref() const; StrBlobPtr& incr(); private: std::shared_ptr<vector<string >> check(size_t,const string&) const; weak_ptr<vector<string>> wptr; size_t curr; }; shared_ptr<vector<string >> StrBlobPtr::check(size_t sz, const string& msg) const { shared_ptr<vector<string >> spv = wptr.lock(); if(!spv){ throw runtime_error(" unbound StrBlobPtr"); } if(sz > spv->size()){ throw range_error(msg); } return spv; } string& StrBlobPtr::deref()const{ auto p = check(curr,"dereference past end"); return (*p)[curr]; } StrBlobPtr& StrBlobPtr::incr() { check(curr,"increment past end of StrBlobPtr"); ++curr; return *this; } StrBlobPtr StrBlob::begin() { return StrBlobPtr(*this); } StrBlobPtr StrBlob::end() { return StrBlobPtr(*this, data->size()); } //begin 和 end要放在StrBlobPtr定以后再实现,不然编译不过

12.20

int main() { StrBlob b; ifstream ifs("test_2.txt"); string str; int count = 0; while (ifs >> str) { b.push_back(str); count++; } StrBlobPtr begin = b.begin(); for(int i = 0 ; i < count ;i++, begin.incr()){ cout << begin.deref() << ends; } for (;;); return 0; }

begin和end没有定义!=比较符,不能直接比较后输出,需要再定义个计数器来进行计算当前个数操作

12.21

各有好处,练习里的写法对运算符分析熟练后,看起来比原版本的简洁

12.22

构造函数时候将传入的StrBlob改成const类型

ConstStrBlobPtr(const StrBlob& a, size_t sz = 0) :wptr(a.data), curr(sz) {}

12.23

int main() { char a[] = "aaasd"; char b[] = "asdasdas"; size_t size = sizeof(a) + sizeof(b); char * charArray = new char[size]; memset(charArray, 0, sizeof(charArray)); strcat_s(charArray, size, a); strcat_s(charArray, size, b); cout << charArray << endl; string as = "qeqeqweqw"; string bs = "asdasdasd"; size_t size_s = as.size() + bs.size(); char * stringArray = new char [size_s]; int slot = 0; for(int i = 0 ; as[i] != '\0'; i++){ *(stringArray+ slot) = as[i]; slot++; } for (int i = 0; bs[i] != '\0'; i++) { *(stringArray + slot) = bs[i]; slot++; } cout << stringArray<< endl; for (;;); return 0; }

12.24

int main() { string tmp; cin >> tmp; char* a = new char [tmp.size()]; for(size_t i = 0; i < tmp.size(); i ++){ *(a+i) = tmp[i]; } *(a + tmp.size())= '\0'; cout << a << endl; for (;;); return 0; }用传入的对象来定义动态数组的长度

12.25

delete [] pa;
转载请注明原文地址: https://www.6miu.com/read-2630463.html

最新回复(0)