Using shared_ptr with an array of objects

I looked through several guides on common C ++ pointers, and I have a few questions that I tried to find answers on the Internet without any luck.

Consider the following code:

class A{
    int v,u;
public:
    A(){}
    A(int p1, int p2): v(p1), u(p2) {}
    ~A(){};
};

void f()
{
    shared_ptr<A> c(new A[5]);
    // Is it correct that this causes a memory leak because...
    //... the default deleter only deletes c[0] ?
    // If yes, is this still true for C++17 and C++20 ?

    shared_ptr<A> d(new A[5], [](A* ptr){ delete [] ptr;});
    // how to pass non-default constructor argument in this case ?
}

int main(){
    f();
}

Questions:
1- Is the user deleting a MUST with an array of objects?
2- How to pass a parameter to a constructor other than the default?
3- Can a custom debugger be a free or member function? (Not lambda).

Notes:
1- Compiler flags: -std=gnu++11 -fext-numeric-literals -std=c++11 -std=c++14 "-D MS_STDLIB_BUGS=0"
2- g ++ with MinGW64 on code blocks.
3- However, I am interested to know this as a whole.

+4
source share
1 answer

1- ?

, ++ 17, std:: shared_ptr.

- delete ptr if T is not an array type; delete[] ptr if T is an array type (since C++17) .

, ++ 17 deleter ( std:: default_delete).

2 , ?

std:: make_shared ++ 20.

template<class T> shared_ptr<T> make_shared(std::size_t N, const std::remove_extent_t<T>& u); 
(4)   (since C++20)  (T is U[])

template<class T> shared_ptr<T> make_shared(const std::remove_extent_t<T>& u); 
(5)   (since C++20)  (T is U[N])

u.

, new A[5] { A{0, 0}, A{1, 1}, ...}.

3- ? ( ).

-.

+4

Source: https://habr.com/ru/post/1696340/


All Articles