C++ - std::make_shared
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