Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

c++ - smart pointers and arrays

How do smart pointers handle arrays? For example,

void function(void)
{
    std::unique_ptr<int> my_array(new int[5]);
}

When my_array goes out of scope and gets destructed, does the entire integer array get re-claimed? Is only the first element of the array reclaimed? Or is there something else going on (such as undefined behavior)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It will call delete[] and hence the entire array will be reclaimed but I believe you need to indicate that you are using an array form of unique_ptrby:

std::unique_ptr<int[]> my_array(new int[5]);

This is called as Partial Specialization of the unique_ptr.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...