Home Item 17 - shared_ptr Supports for Creating Dynamic Arrays (English)
Post
Cancel

Item 17 - shared_ptr Supports for Creating Dynamic Arrays (English)

Support for Creating Dynamic Arrays

In C++11, std::shared_ptr does not support creating dynamic arrays. If you forgot, you can check this article.

C++17 introduced support for this, making the functionality of std::shared_ptr more comprehensive.

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <memory>

class Resource {
 public:
     Resource() { std::cout << "Resource acquired : " << this << "\n"; }
     ~Resource() { std::cout << "Resource destroyed : " << this << "\n"; }
};

int main() {
    std::cout << "~Enter Scope" <<std::endl;
    {
        std::shared_ptr<Resource[]> res1 = std::make_shared<Resource[]>(3);
    }
    std::cout << "~Leave Scope" <<std::endl;
     return 0;
}

Execution result:

Desktop View

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍