gpt4 book ai didi

c++ - unique_ptr 用于数组特化的 lambda 自定义删除器

转载 作者:IT老高 更新时间:2023-10-28 12:45:31 28 4
gpt4 key购买 nike

我最近开始将大量现有 C++ 应用程序代码移植到 C++11,现在我正在转换为新的智能指针 std::unique_ptrstd::shared_ptr,我有一个关于自定义删除器的具体问题。我想添加一个 lambda 记录器来查看我的删除被调用的位置,但我无法获得要编译的数组特化版本。非常感谢您的建议。

我一直在寻找用于 VC++10GCC 4.5.2+unique_ptr 的数组特化自定义删除器的示例,但未果。强>。我想在 lambda 中调用删除器时打印一条日志消息 - 主要是为了确保我认为超出范围的所有指针都在这样做。这对于特化的数组版本是否可行?我可以让它与非数组版本一起工作,如果我将外部结构“MyArrayDeleter”作为第二个参数传递,我也可以让它与数组特化一起工作。还有一件事,是否可以删除丑陋的 std::function,因为我认为我可以让 lambda 签名解决这个问题。

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> ]

最佳答案

怎么样:

auto deleter=[&](int* ptr){...};
std::unique_ptr<int[], decltype(deleter)> ptr4(new int[4], deleter);

关于c++ - unique_ptr<T> 用于数组特化的 lambda 自定义删除器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10319009/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com