Tôi vừa mới bắt đầu porting nhiều C++ hiện tại của tôi mã ứng dụng để giao cho C++ 11 và bây giờ mà tôi đang chuyển sang các con trỏ thông minh mới std :: unique_ptr và std: : shared_ptr, tôi có câu hỏi cụ thể về các thông số tùy chỉnh. Tôi muốn thêm một logger lambda để xem nơi xóa của tôi đang được gọi nhưng tôi không thể có được phiên bản chuyên môn mảng để biên dịch. Lời khuyên sẽ được đánh giá rất nhiều.unique_ptr <T> lambda tùy chỉnh deleter cho chuyên môn mảng
Tôi đã được tìm kiếm trong vô vọng cho một ví dụ về một deleter tùy chỉnh cho mảng chuyên môn unique_ptr cho VC++ 10 hoặc GCC 4.5.2+. Tôi muốn in một thông điệp tường trình khi các deleters được gọi trong một lambda - chủ yếu để đảm bảo rằng tất cả các con trỏ mà tôi nghĩ là đi ra khỏi phạm vi đang làm như vậy. Điều này có thể cho phiên bản mảng chuyên môn không? Tôi có thể làm cho nó làm việc với phiên bản không mảng, và tôi cũng có thể làm cho nó hoạt động với một chuyên môn mảng nếu tôi chuyển một cấu trúc bên ngoài "MyArrayDeleter" làm đối số thứ hai. Một điều nữa, nó sẽ có thể loại bỏ các xấu xí std :: chức năng như tôi nghĩ rằng tôi có thể để cho con số chữ ký lambda mà ra.
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<int, MySimpleDeleter> ptr1(new int(5));
// example 2 - correctly calls MyArrayDeleter where delete[] is called
std::unique_ptr<int[], MyArrayDeleter> ptr2(new int[5]);
// example 3 - this works (but default_delete<int[]> 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<int[], std::default_delete<int[]>> ptr2(new int[100]);
// example 3 - this lambda is called correctly - I want to do this for arrays
std::unique_ptr<int, std::function<void (int *)>> 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<int[], std::function<void (int *)>> 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<void (int *)>
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<void (int *)>
1> ]
ví dụ 3 đã lưu tôi .. cảm ơn –