12.1.5节练习

继承上一次的操作,在unique_ptr中自定义 释放函数的过程中又这样的操作:

unique_ptr<MyClass, decltype(freefuc)*> p2(new MyClass, freefuc);   这里的freefuc的参数必须是  freefuc(Myclass *p); 就像下面这段代码一样。

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <memory>
#include <initializer_list>

using namespace std;
class MyClass{
public:
	int a;
	string b;
	MyClass(): a(2), b("ilove"){
	}
};
//设计程序 验证unique_ptr的自定义释放函数的用法

void freenew(MyClass *my_ptr){
	delete my_ptr;
	cout << "delete success!!" << endl;
}

void subfuc(){
	unique_ptr<MyClass, decltype(freenew)*> my_ptr(new MyClass, freenew);
	cout << my_ptr->a << my_ptr->b << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	subfuc();
	return 0;
}

练习12.16:如果你试图拷贝或者赋值unique_ptr,编译器并不总是能给出易于解释的错误信息。编写包含这种错误信息的程序,观察编译器如何诊断这种错误。

错误	2	error C2207: “std::_Unique_ptr_base<_Ty,_Dx,_Empty_deleter>::_Mydel”: 类模板的成
员无法获取函数类型	c:\program files (x86)\microsoft visual studio 12.0\vc\include\memory	
1275	1	ConsoleApplication1

练习12.17:下面的unique_ptr声明中,哪些是合法的,哪些是可能导致后续的程序错误?解释每个错误的问题在哪里。

int ix = 1024, *pi = &ix, *pi2 = new int(2048);
typedef unique_ptr<int> IntP;
(a) IntP p0(ix);  //错误 ix是int型无法初始化一个指针
(b) IntP p1(pi); // 正确  用一个内置指针初始化一个智能指针
(c) Intp p2(pi2); // 正确   理由同上
(d) IntP p3(&ix);
(e) Intp p4(new int(2048));
(f) Intp p5(p2.get());  //正确   但是会出现隐患   比如当一个unique_ptr失效后  后面一个就不能正常运行

练习12.18:shared_ptr为什么没有release成员?

答:release成员的只要作用是  转移原有指针的控制权  原有指针将被置空   shared_ptr可以多个指针管理一个内存  所以这个没有必要先release   

猜你喜欢

转载自blog.csdn.net/xnnswmzdszyd/article/details/90301509