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