На этот вопрос уже есть ответ здесь:
Недавно я начал портировать большое количество кода моего существующего приложения C++ на C++11, и теперь, когда я перехожу на новые интеллектуальные указатели std ::unique _ptr и std ::shared _ptr , У меня есть конкретный вопрос о пользовательских удалениях. Я хочу добавить лямбда-логгер, чтобы увидеть, где вызываются мои удаления, но я не могу скомпилировать версию специализации массива. Совет был бы очень признателен.
Я тщетно искал пример пользовательского удаления для специализации массива уникальный _указатель для VC++10 или GCC 4.5.2+ . Я хотел бы напечатать сообщение журнала, когда в лямбде -вызываются средства удаления, в основном, чтобы убедиться, что все указатели, которые, как я думаю, выходят за рамки, делают это. Возможно ли это для массивной версии специализации? Я могу заставить его работать с версией без массива, а также могу заставить его работать со специализацией массива, если я передам внешнюю структуру «MyArrayDeleter» в качестве второго аргумента. Еще одна вещь: можно ли удалить уродливую std ::функцию , поскольку я думал, что могу позволить лямбда-сигнатуре понять это.
struct MySimpleDeleter {
void operator()(int* ptr) const {
printf("Deleting int pointer!\n");
delete ptr;
}
};
struct MyArrayDeleter {
void operator()(int* ptr) const {
printf("Deleting Array[]!\n");
delete [] ptr;
}
};
{
// example 1 - calls MySimpleDeleter where delete simple pointer is called
std::unique_ptr ptr1(new int(5));
// example 2 - correctly calls MyArrayDeleter where delete[] is called
std::unique_ptr ptr2(new int[5]);
// example 3 - this works (but default_delete would have been passed
// even if I did not specialize it as it is the default second arg
// I only show it here to highlight the problem I am trying to solve
std::unique_ptr> ptr2(new int[100]);
// example 3 - this lambda is called correctly - I want to do this for arrays
std::unique_ptr> ptr3(
new int(3), [&](int *ptr){
delete ptr; std::cout << "delete int* called" << std::endl;
});
// example 4 - I cannot get the following like to compile
// PLEASE HELP HERE - I cannot get this to compile
std::unique_ptr> ptr4(
new int[4], [&](int *ptr){
delete []ptr; std::cout << "delete [] called" << std::endl;
});
}
The compiler error is as follows:
The error from the compiler (which complains about the new int[4] for ptr4 below is:
'std::unique_ptr<_Ty,_Dx>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty,_Dx>'
1> with
1> [
1> _Ty=int [],
1> _Dx=std::tr1::function
1> ]
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(2513) : see declaration of 'std::unique_ptr<_Ty,_Dx>::unique_ptr'
1> with
1> [
1> _Ty=int [],
1> _Dx=std::tr1::function
1> ]