In C++11, if you are using shared_ptr to manage a dynamic array, you need to manually develop a delete device.
Auto SP = std::shared_ptr (new Int[len], [] (char *p) {delete []p;}];
However, every time you manually specify a bit of trouble, after consulting the data, you can use shared_ptr to create a factory function for a dynamic array.
The specific use is as follows:
#include <iostream>
#include <memory>
#include <string.h>
using namespace std;
Template <typename t>
shared_ptr<t> make_shared_array (size_t size)
{
//default_ Delete is the default undelete in STL return
shared_ptr<t> (new T[size], default_delete<t[]> ());
}
int main ()
{
Auto Sp_array = make_shared_array<char> (m);
strcpy (Sp_array.get (), "Hello smart pointer");
Sp_array.get () [0] = ' a ';
cout << sp_array << Endl;
Use the original pointer to complete the same function:
auto Str_array = new char[100];
strcpy (Str_array, "Hello old Pointer");
Str_array[0] = ' a ';
cout << str_array << Endl;
delete [] Str_array;
return 0;
}
The output results are:
Aello Smart pointer
Aello old pointer
Note that we often need to manipulate an element in a dynamic array, but shared_ptr does not provide the [] operator.
However, we can use Sp.get () first to get the original pointer, and then the original pointer to the subscript operation.
The UNIQUE_PTR provides support for dynamic arrays, and specifies that the deletion is an optional option. You can also use the subscript operation directly:
#include <iostream>
#include <memory>
#include <string.h>
using namespace std;
Class MClass
{public
:
mclass ()
{
mem = new char[100];
cout << "MClass constructor" << Endl;
}
~mclass ()
{
delete [] mem;
cout << "MClass deconstrucotr" << Endl;
Public
:
char *mem;
};
int main ()
{
std::unique_ptr<mclass[]> up (new mclass[2]);
strcpy (Up[0].mem, "Hello Unique_ptr");
cout << up[0].mem << Endl;
return 0;
}
The output of the program is:
MClass Constructor
MClass Constructor
Hello Unique_ptr
MClass DECONSTRUCOTR
MClass DECONSTRUCOTR
PS: The smart pointer can only release its own direct point of memory, if the previous code in the MClass class of the destructor forgot to release the Mem, will still cause memory leaks.