std::make_shared初始化传入指针地址还是数字
时间: 2023-11-16 13:05:48 浏览: 19
`std::make_shared` 初始化的时候可以传入指针地址或者其他的值(如数字)。它会创建一个新的 `std::shared_ptr` 对象并将其初始化为给定值的指针。例如:
```
int x = 10;
auto p1 = std::make_shared<int>(&x); // p1 指向 x 的地址
auto p2 = std::make_shared<int>(20); // p2 指向新分配的 int 类型的内存,并将值初始化为 20
```
注意:`std::make_shared` 会使用一次内存分配来创建对象和 `std::shared_ptr` 对象本身,这可能比直接使用 `new` 和 `std::shared_ptr` 的构造函数效率更高。
相关问题
std::make_shared 初始化string
您可以使用 `std::make_shared` 来初始化 `std::string`。这是一个指向 `std::string` 的智能指针的示例代码:
```cpp
#include <iostream>
#include <memory>
#include <string>
int main() {
std::shared_ptr<std::string> ptr = std::make_shared<std::string>("Hello, World!");
std::cout << *ptr << std::endl;
return 0;
}
```
在这个示例中,`std::make_shared<std::string>("Hello, World!")` 会创建一个指向字符串 "Hello, World!" 的 `std::shared_ptr<std::string>`。然后,我们通过解引用指针 `*ptr` 来访问字符串,并将其输出到标准输出流中。
运行此代码将输出:`Hello, World!`
请注意,`std::make_shared` 的好处是它将分配内存和初始化对象的任务合并在一起,从而提高了性能。
boost::make_shared和std::make_shared
boost::make_shared和std::make_shared都是用于创建智能指针的函数模板。它们的作用是在堆上创建一个对象,并返回一个指向该对象的智能指针。
boost::make_shared是Boost库中的函数模板,而std::make_shared是C++标准库中的函数模板。它们的功能和用法基本相同,都可以用来创建shared_ptr和weak_ptr。
使用make_shared函数模板可以避免显式地使用new操作符来创建对象,并且可以确保对象和引用计数的内存分配在一次内存分配中完成,从而提高了性能和内存利用率。
下面是使用boost::make_shared和std::make_shared的示例代码:
```cpp
#include <iostream>
#include <memory>
#include <boost/make_shared.hpp>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor" << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor" << std::endl;
}
};
int main() {
// 使用boost::make_shared创建shared_ptr
boost::shared_ptr<MyClass> ptr1 = boost::make_shared<MyClass>();
// 使用std::make_shared创建shared_ptr
std::shared_ptr<MyClass> ptr2 = std::make_shared<MyClass>();
return 0;
}
```
在上面的示例中,我们分别使用boost::make_shared和std::make_shared创建了一个名为ptr1和ptr2的shared_ptr对象,它们都指向一个MyClass对象。当程序结束时,智能指针会自动释放内存,调用MyClass的析构函数。
需要注意的是,使用make_shared函数模板创建的智能指针对象不能使用delete操作符来释放内存,因为内存的释放是由智能指针自动管理的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)