第十二章 习题12-1-习题12-10

习题12-1

4个,b2被销毁了,b1还存在,但是他们指向的是同一个vector;

习题12-2

在函数()后加一个const即可

习题12-3

不需要,因为push_back和pop_back会改变元素;

习题12-4

因为 size_type 是一个无符号整型,当传递给 check 的参数小于 0 的时候,参数值会转换成一个正整数。

习题12-5

不好说。。。

参考答案:构造函数不是 explicit 的,意味着可以从 initializer_list 隐式转换为 StrBlob。在 StrBlob 对象中,只有一个数据成员 data,而 StrBlob 对象本身的含义,也是一个管理字符串的序列。因此,从 initializer_list 到 StrBlob 的转换,在逻辑上是可行的。而这个设计策略的缺点,可能在某些地方我们确实需要 initializer_list,而编译器仍会将之转换为 StrBlob。

习题12-6

#include <vector>
#include <memory>
#include<iostream>
using namespace std;
vector<int> *f1()
{
	return new vector<int>;
}
void f2(vector<int> *p)
{
	int k;
	while (cin >> k)
		(*p).push_back(k);
}
void f3(vector<int> *p)
{
	for (auto it : *p)
		cout << it << "  ";
	cout << endl;
}
void main()
{
	vector<int> *vp = f1();
	f2(vp);
	f3(vp);
	delete vp;
}

习题12-7

注意:一开始我直接 return shared_ptr<vector<int>>(),程序报错,因为默认初始化的指针是一个空指针。

#include <vector>
#include <memory>
#include<iostream>
using namespace std;
shared_ptr<vector<int>> f1()
{
	return make_shared<vector<int>>();
}
void f2(shared_ptr<vector<int>> p)
{
	int k;
	while (cin >> k)
		(*p).push_back(k);
}
void f3(shared_ptr<vector<int>> p)
{
	for (auto it : *p)
		cout << it << "  ";
	cout << endl;
}
void main()
{
	shared_ptr<vector<int>> vp = f1();
	f2(vp);
	f3(vp);
}

习题12-8

有错误,没有释放指针;

习题12-9

r 和 q 指向 42,而之前 r 指向的 100 的内存空间并没有被释放,因此会发生内存泄漏。r2 和 q2 都是智能指针,当对象空间不被引用的时候会自动释放。

习题12-10

正确,一开始对为什么正确不是很清楚,直到看到答案代码,这里shared_ptr<int> (p)用p初始化一个临时变量 tem=shared_ptr<int> (p),然后将tem放入函数中,这样引用计数为2.

#include <iostream>
#include <vector>
#include <string>
#include <memory>

void process(std::shared_ptr<int> ptr)
{
	std::cout << "inside the process function:" << ptr.use_count() << "\n";
}

int main()
{
	std::shared_ptr<int> p(new int(42));
	process(std::shared_ptr<int>(p));

	/**
	* codes below shows how the reference count change.
	*/
	std::cout << p.use_count() << "\n";
	auto q = p;
	std::cout << p.use_count() << "\n";
	std::cout << "the int p now points to is:" << *p << "\n";
	return 0;
}

输出为:
inside the process function:2
1
2
the int p now points to is:42
请按任意键继续. . .

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值