写一个unique_ptr<T[]> 解引用的例子
时间: 2023-12-26 19:05:44 浏览: 31
下面是一个unique_ptr<T[]>解引用的例子:
```cpp
#include <iostream>
#include <memory>
using namespace std;
int main()
{
unique_ptr<int[]> arr(new int[5]{1, 2, 3, 4, 5});
for (int i = 0; i < 5; i++)
{
cout << arr[i] << " "; // 通过数组下标访问元素
}
cout << endl;
int* ptr = arr.get();
for (int i = 0; i < 5; i++)
{
cout << *(ptr + i) << " "; // 通过指针访问元素
}
cout << endl;
return 0;
}
```
输出结果为:
```
1 2 3 4 5
1 2 3 4 5
```
在上面的例子中,我们定义了一个unique_ptr<int[]>指向包含5个整数的动态数组。我们可以通过数组下标和指针来访问数组中的元素。注意,我们不能使用解引用运算符*来访问unique_ptr<T[]>中的元素。
相关问题
std::vector<std::unique_ptr<>>
std::vector<std::unique_ptr<>>是一种容器类型,它可以存储指向动态分配对象的智能指针。每个智能指针都负责管理其指向的对象的内存释放。下面是一个示例演示如何使用std::vector<std::unique_ptr<>>:
```cpp
#include <iostream>
#include <memory>
#include <vector>
class MyObject {
public:
MyObject(int value) : m_value(value) {
std::cout << "Constructing MyObject with value: " << m_value << std::endl;
}
~MyObject() {
std::cout << "Destructing MyObject with value: " << m_value << std::endl;
}
void printValue() {
std::cout << "Value: " << m_value << std::endl;
}
private:
int m_value;
};
int main() {
std::vector<std::unique_ptr<MyObject>> objects;
objects.push_back(std::make_unique<MyObject>(1));
objects.push_back(std::make_unique<MyObject>(2));
objects.push_back(std::make_unique<MyObject>(3));
for (const auto& obj : objects) {
obj->printValue();
}
return 0;
}
```
这个例子创建了一个std::vector<std::unique_ptr<MyObject>>,并向其中添加了三个MyObject对象。当vector离开作用域时,它会自动释放所有的MyObject对象。在循环中,我们打印了每个对象的值。
unique_ptr<int> p = new int()
这行代码是错误的,因为 `new int()` 返回的是一个指向动态分配的整型对象的指针,而 `unique_ptr` 的构造函数需要传入一个指针作为参数,而不是直接将指针赋值给 `unique_ptr`。
要将动态分配的对象交给 `unique_ptr` 来管理,正确的方式是使用 `std::make_unique` 函数,或者使用 `std::unique_ptr` 的构造函数进行初始化。
使用 `std::make_unique` 的示例代码如下:
```cpp
std::unique_ptr<int> p = std::make_unique<int>();
```
或者使用 `std::unique_ptr` 的构造函数进行初始化的示例代码如下:
```cpp
std::unique_ptr<int> p(new int());
```
这样,`p` 就会成为一个管理着动态分配的整型对象的 `unique_ptr`。