12.6
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
vector<int>* factory()
{
return new vector<int>();
}
void add_element(vector<int> *pvec)
{
int i;
while (cin >> i)
pvec->push_back(i);
}
void print_vec(vector<int> *pvec)
{
for (auto i : *pvec)
cout << i << " ";
cout << endl;
}
int main()
{
auto pv = factory();
cout << "input some numbers: " << endl;
add_element(pv);
print_vec(pv);
delete pv;
return 0;
}
12.7
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
shared_ptr<vector<int>> factory()
{
return make_shared<vector<int>>();
}
void add_element(shared_ptr<vector<int>> pvec)
{
int i;
while (cin >> i)
pvec->push_back(i);
}
void print_vec(shared_ptr<vector<int>> pvec)
{
for (auto i : *pvec)
cout << i << " ";
cout << endl;
}
int main()
{
auto pv = factory();
cout << "input some numbers: " << endl;
add_element(pv);
print_vec(pv);
return 0;
}
12.8 int *p = new int; 如果分配失败,new抛出std::bad_alloc; int *p = new (nothrow) int; 如果分配失败,new不抛出异常,返回一个空指针;所以依照题意应该使用nothrow版本。
12.9 使用普通指针,r原先指向的内存(保存值100)无法释放;使用智能指针,r2原先指向的内存会自动释放。
12.10 正确,用p创建shared_ptr赋予ptr,引用次数为2,函数执行完毕引用计数为1,正确。
12.11 错误,p.get()得到的是普通指针,参数ptr引用次数为1,函数执行完毕,ptr引用计数为0,会释放内存,导致p成为空悬指针。
12.12 (a)合法;(b)不合法,不能将内置指针隐式转换为智能指针;(c)不合法,不能将内置指针隐式转换为智能指针; (d) 合法,但程序错误,p会成为空悬指针。
12.13 sp会成为空悬指针。
12.14
#include <iostream>
#include <memory>
using namespace std;
struct destination {};
struct connection {};
connection connect(destination *dest)
{
cout << "connect... " << endl;
return connection();
}
void disconnect(connection)
{
cout << "disconnect... " << endl;
}
void end_connection(connection *p)
{
disconnect(*p);
}
void f(destination &d)
{
cout << "f use shared_ptr" << endl;
connection c = connect(&d);
shared_ptr<connection> p(&c, end_connection);
cout << "quit f" << endl;
}
int main()
{
destination d;
f(d);
return 0;
}
12.15
#include <iostream>
#include <memory>
using namespace std;
struct destination {};
struct connection {};
connection connect(destination *dest)
{
cout << "connect... " << endl;
return connection();
}
void disconnect(connection)
{
cout << "disconnect... " << endl;
}
void f(destination &d)
{
cout << "f use shared_ptr" << endl;
connection c = connect(&d);
/* use lambda */
shared_ptr<connection> p(&c, [](connection *ptr) { disconnect(*ptr); });
cout << "quit f" << endl;
}
int main()
{
destination d;
f(d);
return 0;
}
本文主要探讨了C++ Primer第五版中12.1.2至12.1.4节关于智能指针和内存管理的内容。详细解析了new运算符在内存分配失败时的行为,以及普通指针和智能指针在释放内存方面的差异。同时,通过一系列问题和解答,强调了智能指针在管理动态内存时如何避免空悬指针和内存泄漏,以及隐式类型转换的限制。
999

被折叠的 条评论
为什么被折叠?



