简体   繁体   中英

Using shared_ptr with array of objects

I watched some tutorials about C++ shared pointers, and I have a few questions that I tried to find answers for on the Internet with no 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 custom deleter a MUST with array of objects?
2- How to pass parameter to the constructor other than default?
3- Can the custom deleter 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 in general.

1- Is the custom deleter is a MUST with array of objects?

No since C++17, if you specify the correct template parameter type for std::shared_ptr .

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

Before C++17 you have specify a custom deleter (might use std::default_delete ).

2- How to pass parameter to the constructor other than default?

You can achieve this via std::make_shared since C++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]) 

every element is initialized from the default value u.

Or do sth manually like new A[5] { A{0, 0}, A{1, 1}, ...} .

3- Can the custom deleter be a free or member function? (Not lambda).

It could be a free or static member function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM