Logo

Programming-Idioms

History of Idiom 209 > diff from v12 to v13

Edit summary for version 13 by hose:
[C++] Added second alternative

Version 12

2021-08-16, 10:03:39

Version 13

2021-08-16, 10:22:20

Idiom #209 Type with automatic deep deallocation

Declare a type t which contains a string s and an integer array n with variable size, and allocate a variable v of type t. Allocate v.s and v.n and set them to the values "Hello, world!" for s and [1,4,9,16,25], respectively. Deallocate v, automatically deallocating v.s and v.n (no memory leaks).

Idiom #209 Type with automatic deep deallocation

Declare a type t which contains a string s and an integer array n with variable size, and allocate a variable v of type t. Allocate v.s and v.n and set them to the values "Hello, world!" for s and [1,4,9,16,25], respectively. Deallocate v, automatically deallocating v.s and v.n (no memory leaks).

Variables
t,s,n,v
Variables
t,s,n,v
Code
#include <string>
using namespace std::string_literals;
#include <vector>
#include <memory>

struct t {
    std::string s;
    std::vector<int> n;
};

auto v = std::make_unique<t>("Hello, world!"s, decltype(t::n){1, 4, 9, 16, 25});

v.reset();
Code
#include <string>
using namespace std::string_literals;
#include <vector>
#include <memory>

struct t {
    std::string s;
    std::vector<int> n;
};

auto v = std::make_unique<t>(
    "Hello, world!"s,
    decltype(t::n){1, 4, 9, 16, 25}
);
v.reset();

// Automatically:
void fn(){
    auto v = std::make_unique<t>(
        "Hello, world!"s,
        decltype(t::n){1, 4, 9, 16, 25}
    );
}
Comments bubble
v.reset() is explicit deallocation, the object is also automatically deallocated when it goes out of scope.
Comments bubble
v.reset() is explicit deallocation, the object is also automatically deallocated when it goes out of scope.
Doc URL
https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique
Doc URL
https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique