C++ - std::make_shared

C++ - std::make_shared

function template - 函数模板
Defined in header <memory> - 定义于头文件 <memory>
creates a shared pointer that manages a new object. - 创建管理一个新对象的共享指针。

1. std::make_shared

template <class T, class... Args>
  shared_ptr<T> make_shared (Args&&... args);

Make shared_ptr.

Allocates and constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr<T> that owns and stores a pointer to it (with a use count of 1).
分配并构造类型为 T 的对象,将 args 传递给其构造函数,然后返回类型为 shared_ptr<T> 的对象,该对象拥有并存储指向它的指针 (使用计数为 1)。

This function uses ::new to allocate storage for the object. A similar function, allocate_shared, accepts an allocator as argument and uses it to allocate the storage.
这个函数使用 ::new 为对象分配存储空间。类似的函数 allocate_shared 接受一个 allocator 作为参数,并使用它来分配存储空间。

2. Parameters

args
List of elements passed to T's constructor. - 传递给 T 的构造函数的元素列表。
Args is a list of zero or more types. - Args 是零个或多个类型的列表。

3. Return value

A shared_ptr object that owns and stores a pointer to a newly allocated object of type T.
一个 shared_ptr 对象,它拥有并存储指向类型为 T 的新分配对象的指针。

std::shared_ptr of an instance of type T.
类型 T 实例的 std::shared_ptr

4. Examples

4.1 std::make_shared

//============================================================================
// Name        : std::make_shared
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <memory>

int main()
{
	std::shared_ptr<int> cheng = std::make_shared<int>(10);
	// same as:
	std::shared_ptr<int> strong(new int(10));

	auto yong = std::make_shared<int>(20);

	auto qiang = std::make_shared<std::pair<int, int>>(30, 40);

	std::cout << "*cheng: " << *cheng << '\n';
	std::cout << "*strong: " << *strong << '\n';
	std::cout << "*yong: " << *yong << '\n';
	std::cout << "*qiang: " << qiang->first << ' ' << qiang->second << '\n';

	return 0;
}

*cheng: 10
*strong: 10
*yong: 20
*qiang: 30 40
请按任意键继续. . .
assignment [ə'saɪnmənt]:n. 任务,布置,赋值

References

http://www.cplusplus.com/reference/memory/make_shared/
https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yongqiang Cheng

梦想不是浮躁,而是沉淀和积累。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值