一、VS例子
// Test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <thread>
#include <memory>
#include <iostream>
#include <assert.h>
class A
{
public:
A()
{
std::cout << "A Create" << std::endl;
}
~A()
{
std::cout << "A Destroy" << std::endl;
}
void fun()
{
std::cout << "A Fun" << std::endl;
}
private:
};
int main()
{
A* a = new A();
std::unique_ptr<A> myPtr(a);
myPtr->fun();//重载的->,可以理解为直接返回a指针
(*myPtr).fun();//直接取指向的对象,所以不再使用指针
std::unique_ptr<A> myOtherPtr = std::move(myPtr);//myPtr将指向a的权利移动给myOtherPtr,myPtr变为空指针
assert(myPtr != nullptr);
myOtherPtr.reset();
assert(myOtherPtr != nullptr);
assert(a != nullptr);
getchar();
return 0;
}
二、Qt例子
mainwindow.h:
class A { public: A() { qDebug()<<"A"; } ~A() { qDebug()<<"~A"; } }; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; std::unique_ptr<A> uptr_AllData; private slots: };
mainwindow.cpp:
{ std::unique_ptr<A> tmepPtr(new A);//打印A uptr_AllData = std::move(tmepPtr);// }
现象:
在new A的时候打印A,在窗口关闭后,自动回收A的内存,打印~A。
三、智能指针数组
mainwindow.h
class A { public: A() { qDebug()<<"A"; } ~A() { qDebug()<<"~A"; } void print() { qDebug()<<"print function"; } }; class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; queue<unique_ptr<A>> allPacket; private slots: void on_pushButton_clicked(); };
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); { unique_ptr<A> data(new A); allPacket.push(std::move(data)); } } void MainWindow::on_pushButton_clicked() { allPacket.front()->print(); allPacket.pop(); }
现象:
在new的时候打印A,在pop之后打印~A
四、智能指针作为参数传递
1、看函数原型
2、传参
核心:转移指针所有权【std::move】,把所有权从实参传到形参
PS:
1、智能指针的核心就是在析构的时候自动帮你delete所指向的指针。
2、如果希望将此智能指针作为类的属性,那么在赋值的时候:先生成一个临时的智能指针,再用std::move来赋值给这个属性,否则就必须在声明的时候就初始化。
3、使用此智能指针的优点就是不用自己在析构函数中delete指针。【感觉缺点多多了】