C++ unique_ptr

        unique_ptr 不共享它的指针。它无法复制到其他 unique_ptr,无法通过值传递到函数,也无法用于需要副本的任何标准模板库 (STL) 算法。只能移动unique_ptr这意味着,内存资源所有权将转移到另一 unique_ptr,并且原始 unique_ptr 不再拥有此资源。我们建议你将对象限制为由一个所有者所有,因为多个所有权会使程序逻辑变得复杂。因此,当需要智能指针用于纯 C++ 对象时,可使用 unique_ptr,而当构造 unique_ptr 时,可使用make_unique Helper 函数。

    

      unique_ptr 在 STL 的 <memory> 标头中定义。它与原始指针一样有效,并可用于 STL 容器。将 unique_ptr 实例添加到 STL 容器很有效,因为通过unique_ptr 的移动构造函数,不再需要进行复制操作。

  

#include "stdafx.h"
#include <iostream>
#include <string>
#include <memory>
using namespace std;

class Song
{
public:
	Song(std::string strArtist, std::string strTitle) : artist(strArtist), title(strTitle)
	{

	}
	Song()
	{

	}
	std::string GetArtist() { return artist; };
	std::string GetTitle() { return title; };
private:
	std::string  artist;
	std::string  title;
};


unique_ptr<Song> SongFactory(const std::string& artist, const std::string& title)
{
	return make_unique<Song>(artist,title);
}


void MakeSongs()
{
	auto song = make_unique<Song>("jz","123");
	cout << "---------------------------------" << endl;
	cout << song->GetArtist() << endl;
	cout << song->GetTitle() << endl;

	unique_ptr<Song> song2 = std::move(song);//调用move后  song为空  song2 指向了jz,123
	cout << "---------------------------------" << endl;
	cout << song2->GetArtist() << endl;
	cout << song2->GetTitle() << endl;
	cout << "---------------------------------" << endl;
	if (song != nullptr)
	{
		cout << song->GetArtist() << endl;
		cout << song->GetTitle() << endl;
	}
	else
	{
		cout << "song is nullptr" << endl;
	}

	auto song3 = SongFactory("cyw", "111");
	cout << "---------------------------------" << endl;
	if (song3 != nullptr)
	{
		cout << song3->GetArtist() << endl;
		cout << song3->GetTitle() << endl;
	}
	auto song4 = std::move(song3);
	cout << "---------------------------------" << endl;
	if (song4 != nullptr)
	{
		cout << song4->GetArtist() << endl;
		cout << song4->GetTitle() << endl;
	}


}

int main()
{
	MakeSongs();
	return 0;
}

shared_ptr

点击打开链接

unique_ptr

点击打开链接



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值