smart pointers and arrays

前端 未结 2 416
盖世英雄少女心
盖世英雄少女心 2020-11-27 14:56

How do smart pointers handle arrays? For example,

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

When m

2条回答
  •  猫巷女王i
    2020-11-27 15:46

    Edit: This answer was wrong, as explained by the comments below. Here's what I originally said:

    I don't think std::unique_ptr knows to call delete[]. It effectively has an int* as a member -- when you delete an int* it's going to delete the entire array, so in this case you're fine.

    The only purpose of the delete[] as opposed to a normal delete is that it calls the destructors of each element in the array. For primitive types it doesn't matter.

    I'm leaving it here because I learned something -- hope others will too.

提交回复
热议问题