C++ Primer(5e)第12章习题

12.1

4个元素

12.2

class StrBlob {
public:
	typedef std::vector<std::string>::size_type size_type;
	StrBlob();
	StrBlob(std::initializer_list<std::string> i1);
	size_type size() const { return data->size(); }
	bool empty() const { return data->empty(); }
	// 添加和删除元素
	void push_back(const std::string &t) { data->push_back(t); }
	void pop_back();
	// 元素访问
	std::string& const front();
	std::string& const back();
private:
	std::shared_ptr<std::vector<std::string>> data;
	// 如果data[i]不合法,抛出一个异常
	void check(size_type i, const std::string &msg) const;
};

12.3

不需要,因为要修改类中的元素

12.4

因为i的类型为size_type,此类型为无符号整数

12.5

如果使用了explicit,好处就是函数不能隐式转换,但是缺点也很明显,就是函数只能直接初始化。

12.6

#include
#include
#include

using namespace std;


void Fuc2(istream& is, vector<int>* v)
{
	int val;
	while (is >> val)
		// 这里有个容易模糊的概念: .和->  
		// .是实例化对象,类中普通成员的引用,->是指针类型,是指针引用
		v->push_back(val);
	return v;
}

void Fuc3(vector<int>* v)
{
	for (auto k : *v)
		cout << k << " ";
	cout << endl;
}

int main()
{
	vector<int> *v = new vector<int>;
	Fuc2(cin, v);
	Fuc3(v);
	delete v;
	system("pause");
	return 0;
}

12.7

#include
#include
#include

using namespace std;


void Fuc2(istream& is, shared_ptr<vector<int>> v)
{
	int val;
	while (is >> val)
		v->push_back(val);
}

void Fuc3(shared_ptr<vector<int>> v)
{
	for (auto k : *v)
		cout << k << " ";
	cout << endl;
}

int main()
{
	shared_ptr<vector<int>> v = make_shared<vector<int>>();
	Fuc2(cin, v);
	Fuc3(v);
	system("pause");
	return 0;
}

12.8

bool b() {
	int* p = new int;
	// ...
	return p;
}

没有错误

12.9

第2行:r内存泄漏
第4行:r2指向q2,原r2回收

12.10

shared_ptr<int> p(new int(42));
process(shared_ptr<int>(p));

正确

12.11

process(shared_ptr<int>(p.get()));

p指向的内存被销毁但是p可能还会继续被使用,发生未定义行为

12.12

auto p = new int();
auto sp = make_shared<int>();
(a)process(sp);  // 合法
(b)process(new int());  // 不合法,不能赋内置指针给共享指针
(c)process(p);  // 不合法,和b一样
(d)process(shared_ptr<int>(p));  // 合法

12.13

auto sp = nake_shared<int> ();
auto p = sp.get();
delete p;

sp指向的内存也被删除了

12.17

(a) 不合法,将一个整数赋值到智能指针上
(b) 不合法,将一个普通指针赋值到智能指针上
(c) 合法
(d) 不合法,和b一样
(e) 合法
(f) 合法但是有风险

12.18

因为shared_ptr允许多个指针指向同一个对象

未完待续。。。。(二刷)

你可能感兴趣的:(C++)