std::unique_ptr不支持复制和赋值
std::shared_ptr支持复制和赋值
参考C++ 智能指针的正确使用方式 | 编程沉思录
#include <iostream>
#include <thread>
class PP {
public:
PP(int v) { _v = v; }
~PP() {
printf("=== pp is end. _v: %d\n", _v);
}
private:
int _v = -1;
};
void fun0() {
printf("begin of fun\n");
std::vector<int *> a;
for (int i = 0; i < 10; i++) {
printf("%d\n", i);
int *p = new int[1000 * 1000 * 10];
memset(p , 0, 1000 * 1000 * 10);
if (i == 5) {
p[0] = 66;
p[1] = 67;
int x1 = p[0];
int x2 = p[1];
int x3 = p[2];
printf("%d\n", x1);
printf("%d\n", x2);
printf("%d\n", x3);
}
a.push_back(p);
}
printf("%d\n", a[5][0]);
printf("%d\n", a[5][1]);
printf("sleep 2 seconds\n");
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
printf("end of fun\n");
}
void fun1() {
printf("begin of fun\n");
std::vector<int *> a;
for (int i = 0; i < 10; i++) {
printf("%d\n", i);
std::unique_ptr<int[]> p = std::make_unique<int[]>(1000 * 1000 * 10); // 不管是std::unique_ptr<int[]> p还是std::shared_ptr<int[]> p都会报错
memset(p.get(), 0, 1000 * 1000 * 10);
if (i == 5) {
p[0] = 66;
p[1] = 67;
int x1 = p[0];
int x2 = p[1];
int x3 = p[2];
printf("%d\n", x1);
printf("%d\n", x2);
printf("%d\n", x3);
}
a.push_back(p.get());
}
// 报错,
printf("%d\n", a[5][0]);
printf("%d\n", a[5][1]);
printf("sleep 2 seconds\n");
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
printf("end of fun\n");
}
void fun2() {
printf("begin of fun\n");
std::vector<std::shared_ptr<int []>> a;
std::vector<std::unique_ptr<PP>> b;
//std::vector<std::shared_ptr<PP>> b;
for (int i = 0; i < 10; i++) {
printf("%d\n", i);
//std::shared_ptr<int[]> p(new int[1000 * 1000 * 10]()); // c++17
std::shared_ptr<int[]> p = std::make_unique<int[]>(1000 * 1000 * 10); // c++20
memset(p.get(), 0, 1000 * 1000 * 10);
if (i == 5) {
p[0] = 66;
p[1] = 67;
int x1 = p[0];
int x2 = p[1];
int x3 = p[2];
printf("%d\n", x1);
printf("%d\n", x2);
printf("%d\n", x3);
}
a.push_back(p);
b.push_back(
std::make_unique<PP>(i)
);
}
printf("%d\n", a[5][0]);
printf("%d\n", a[5][1]);
printf("sleep 2 seconds\n");
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
printf("end of fun\n");
}
int main()
{
//fun0(); // 执行完毕返回main, 内存还没释放
//fun1(); // 报错
fun2(); // 执行完毕返回main, 内存已经释放
printf("in main.\nSleep 2 seconds.\n");
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
return 1;
}