#include <iostream>
#include <assert.h>
#include <utility> // pair
#include <memory> // auto_ptr
using namespace std;
int pair_test()
{
pair<char, int> c1('x', 3);
printf("[%c, %d]\n", c1.first, c1.second);
c1 = make_pair('y', 4);
printf("[%c, %d]\n", c1.first, c1.second);
return 0;
}
template<class T>
void BadPrint(std::auto_ptr<T> p)
{
if (p.get() == NULL)
{
cout << NULL;
}
else
{
cout << *p;
}
}
int auto_ptr_test()
{
auto_ptr<int> p1(new int(24));
auto_ptr<int> p2;
int *q1 = new int(12);
int *q2;
p2 = p1; // 赋值完后p1已经为空了
q2 = q1;
*p1 = 1; // 出错
assert(p1.get() == NULL); // p1为空,get()获取其顶层指针
assert(*p2 == 24);
assert(*q1 == 12);
assert(*q2 == 12);
auto_ptr<int> p3;
assert(p3.get() == NULL);
p3.reset(q2); // 让p3管理q2指向的对象
assert(*p3 == 12);
assert(*q1 == 12);
assert(*q2 == 12);
/*
1. 智能指针不能共享指向对象的所有权
2. 智能指针不能指向数组,因为其实现中调用的是delete而非delete[]
3. 智能指针不是万能的
4. 智能指针不能作为容器类的元素
*/
/*
该程序并未像我们所期望的一样*q的值为12,而是会出现runtime error。
因为我们把q作为函数参数传给了BadPrint,因此传递完成后q不再拥有对指向对象的所有权,
而函数内部的局部变量p会接管q所指向对象的所有权,当函数执行完毕退出时,
p的生命期截止,delete掉其所指向对象。
如何避免出错?使用auto_ptr的引用,即void BadPrint(std::auto_ptr<T> &p)?
这是相当糟糕的一种做法。对智能指针使用引用混淆了所有权的问题,
它导致所有权有可能被传递了,也可能没有被传递。无论如何应当避免对auto_ptr使用引用。
*/
std::auto_ptr<int> q(new int(18));
BadPrint(q);
*q = 12; // 此时q已经为空了,出错
return 0;
}
int main(int argc, char* argv[])
{
pair_test();
auto_ptr_test();
return 0;
}
#include <assert.h>
#include <utility> // pair
#include <memory> // auto_ptr
using namespace std;
int pair_test()
{
pair<char, int> c1('x', 3);
printf("[%c, %d]\n", c1.first, c1.second);
c1 = make_pair('y', 4);
printf("[%c, %d]\n", c1.first, c1.second);
return 0;
}
template<class T>
void BadPrint(std::auto_ptr<T> p)
{
if (p.get() == NULL)
{
cout << NULL;
}
else
{
cout << *p;
}
}
int auto_ptr_test()
{
auto_ptr<int> p1(new int(24));
auto_ptr<int> p2;
int *q1 = new int(12);
int *q2;
p2 = p1; // 赋值完后p1已经为空了
q2 = q1;
*p1 = 1; // 出错
assert(p1.get() == NULL); // p1为空,get()获取其顶层指针
assert(*p2 == 24);
assert(*q1 == 12);
assert(*q2 == 12);
auto_ptr<int> p3;
assert(p3.get() == NULL);
p3.reset(q2); // 让p3管理q2指向的对象
assert(*p3 == 12);
assert(*q1 == 12);
assert(*q2 == 12);
/*
1. 智能指针不能共享指向对象的所有权
2. 智能指针不能指向数组,因为其实现中调用的是delete而非delete[]
3. 智能指针不是万能的
4. 智能指针不能作为容器类的元素
*/
/*
该程序并未像我们所期望的一样*q的值为12,而是会出现runtime error。
因为我们把q作为函数参数传给了BadPrint,因此传递完成后q不再拥有对指向对象的所有权,
而函数内部的局部变量p会接管q所指向对象的所有权,当函数执行完毕退出时,
p的生命期截止,delete掉其所指向对象。
如何避免出错?使用auto_ptr的引用,即void BadPrint(std::auto_ptr<T> &p)?
这是相当糟糕的一种做法。对智能指针使用引用混淆了所有权的问题,
它导致所有权有可能被传递了,也可能没有被传递。无论如何应当避免对auto_ptr使用引用。
*/
std::auto_ptr<int> q(new int(18));
BadPrint(q);
*q = 12; // 此时q已经为空了,出错
return 0;
}
int main(int argc, char* argv[])
{
pair_test();
auto_ptr_test();
return 0;
}