std::make_shared怎么用
时间: 2024-01-16 09:18:15 浏览: 31
std::make_shared 是一个模板函数,用于创建一个指定类型的 std::shared_ptr 智能指针对象。它接受可变数量的参数,并将这些参数传递给指定类型的构造函数来创建对象。
下面是一个示例演示如何使用 std::make_shared:
```cpp
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass(int value) : m_value(value) {
std::cout << "Constructor called with value: " << m_value << std::endl;
}
~MyClass() {
std::cout << "Destructor called with value: " << m_value << std::endl; }
private:
int m_value;
};
int main() {
// 使用 std::make_shared 创建一个指向 MyClass 对象的 std::shared_ptr
std::shared_ptr<MyClass> ptr = std::make_shared<MyClass>(42);
// 使用 std::make_shared 创建一个空的 std::shared_ptr
std::shared_ptr<int> emptyPtr = std::make_shared<int>();
return 0;
}
```
输出结果:
```
Constructor called with value: 42
Destructor called with value: 42
Destructor called with value: 0
```
在上面的示例中,我们首先使用 std::make_shared 创建了一个指向 MyClass 对象的 std::shared_ptr,并传递了参数 42 给 MyClass 的构造函数。然后,我们创建了一个空的 std::shared_ptr,没有传递任何参数给构造函数。
需要注意的是,std::make_shared 在创建对象时会分配一块连续的内存来存储对象和引用计数,这样可以提高性能和内存利用率。