C++primer 12.1.2节练习

练习12. 6

 

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 #include <sstream>
 5 #include <set>
 6 #include <map>
 7 #include <algorithm>
 8 #include <vector>
 9 #include <algorithm>
10 #include <iterator>
11 #include <unordered_map>
12 #include <memory>
13 
14 using namespace std;
15 
16 vector<int> * malloc_vector();
17 void read(istream &is, vector<int>* vec);
18 void print(ostream &os, vector<int>* vec);
19 
20 int main()
21 {
22     auto q = malloc_vector();
23     read(cin, q);
24     print(cout, q);
25     system("pause");
26     return 0;
27 }
28 
29 vector<int>* malloc_vector()
30 {
31     vector<int> *p = new vector<int>();
32     return p;
33 }
34 
35 void read(istream & is, vector<int>* vec)
36 {
37     int num;
38     while (is >> num)
39         (*vec).push_back(num);
40 }
41 
42 void print(ostream & os, vector<int>* vec)
43 {
44     for (auto c : *vec)
45         os << c << endl;
46     delete vec;
47     // TODO: 在此处插入 return 语句
48 }

 

 

 

练习12.7

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 #include <sstream>
 5 #include <set>
 6 #include <map>
 7 #include <algorithm>
 8 #include <vector>
 9 #include <algorithm>
10 #include <iterator>
11 #include <unordered_map>
12 #include <memory>
13 
14 using namespace std;
15 
16 vector<int> read(istream &is,vector<int> vec);
17 void print(ostream &os, shared_ptr<vector<int>> p);
18 
19 int main()
20 {
21     vector<int> vec;
22     auto q = make_shared<vector<int>>(read(cin, vec));
23     print(cout, q);
24     system("pause");
25     return 0;
26 }
27 
28 vector<int> read(istream & is,vector<int> vec)
29 {
30     int num;
31     while (is >> num)
32         vec.push_back(num);
33     return vec;
34     // TODO: 在此处插入 return 语句
35 }
36 
37 void print(ostream & os, shared_ptr<vector<int>> p)
38 {
39     for (auto c : *p)
40         os << c << endl;
41 }

练习12.8

p是内置类型的动态内存分配,他是未定义的,返回的也将是未定义的。

网上答案:从程序片段看,可以猜测程序员的意图是通过new返回的指针值来区分内存分配成功或失败——成功返回一个合法指针,转换为整型是一个非零值,可转换为bool值true;分配失败,p得到nullptr,其整型值是0,可转换为bool值false.

 

但普通new调用在分配失败时抛出一个异常bad_alloc,而不是返回nullptr,因此程序不能达到预想目的。

可将new int改为new (nothrow) int 来令new在分配失败时不抛出异常,而是返回nullptr。但这仍然不是一个好方法,应该通过捕获异常或是判断返回的指针来判断true或false,而不是依赖类型转换。

练习12.9

上下两个程序想要执行的功能类似,但是却有着千差万别,下面使用智能指针,当把q2赋值给r2时,q2的引用计数递增,r2的引用计数递减为0,系统自动释放内存,而上面使用new的方法,r的内存没有及时释放,造成内存泄露。程序想让我们知道使用智能指针比我们手动释放内存要好得多。

转载于:https://www.cnblogs.com/wuyinfenghappy/p/7445526.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值