带有 std::vector 的自定义释放器不会被调用
Custom deallocator with an std::vector doesn't get called
我希望这段代码在释放内存时打印 "Hello world" - "Hello ",在 main
中打印 "world"。但是 "Hello" 永远不会被打印出来,这意味着我的解除分配器不会被调用。实施它的正确方法是什么?
#include <iostream>
#include <vector>
class MyAllocator : public std::allocator<uint8_t>
{
public:
void deallocate(uint8_t* data, std::size_t size)
{
std::cout << "Hello ";
std::allocator<uint8_t>::deallocate(data, size);
}
};
int main()
{
{
std::vector<uint8_t, MyAllocator> v(100);
}
std::cout << "world\n";
return 0;
}
我假设它只是调用默认的 std::allocator<uint8_t>::deallocate()
函数,但我没有找到阻止它并使其调用我的函数的方法。
std::allocator
定义成员 template rebind<U>
.
并且 std::vector
正确使用它来确保它分配正确的内存块,具有适当的大小和对齐方式,因此即使您通过了自定义分配器,重新绑定也会导致实际使用标准分配器.
有关分配器的潜在成员,例如 http://en.cppreference.com/w/cpp/concept/Allocator。
事实上,如果您定义重新绑定,您的分配器就会工作:
#include <iostream>
#include <vector>
class MyAllocator : public std::allocator<uint8_t>
{
public:
template <typename U>
struct rebind
{
typedef MyAllocator other;
};
void deallocate(uint8_t* data, std::size_t size)
{
std::cout << "Hello ";
std::allocator<uint8_t>::deallocate(data, size);
}
};
int main()
{
{
std::vector<uint8_t, MyAllocator> v(100);
}
std::cout << "world\n";
return 0;
}
生产:
Hello world
我希望这段代码在释放内存时打印 "Hello world" - "Hello ",在 main
中打印 "world"。但是 "Hello" 永远不会被打印出来,这意味着我的解除分配器不会被调用。实施它的正确方法是什么?
#include <iostream>
#include <vector>
class MyAllocator : public std::allocator<uint8_t>
{
public:
void deallocate(uint8_t* data, std::size_t size)
{
std::cout << "Hello ";
std::allocator<uint8_t>::deallocate(data, size);
}
};
int main()
{
{
std::vector<uint8_t, MyAllocator> v(100);
}
std::cout << "world\n";
return 0;
}
我假设它只是调用默认的 std::allocator<uint8_t>::deallocate()
函数,但我没有找到阻止它并使其调用我的函数的方法。
std::allocator
定义成员 template rebind<U>
.
并且 std::vector
正确使用它来确保它分配正确的内存块,具有适当的大小和对齐方式,因此即使您通过了自定义分配器,重新绑定也会导致实际使用标准分配器.
有关分配器的潜在成员,例如 http://en.cppreference.com/w/cpp/concept/Allocator。
事实上,如果您定义重新绑定,您的分配器就会工作:
#include <iostream>
#include <vector>
class MyAllocator : public std::allocator<uint8_t>
{
public:
template <typename U>
struct rebind
{
typedef MyAllocator other;
};
void deallocate(uint8_t* data, std::size_t size)
{
std::cout << "Hello ";
std::allocator<uint8_t>::deallocate(data, size);
}
};
int main()
{
{
std::vector<uint8_t, MyAllocator> v(100);
}
std::cout << "world\n";
return 0;
}
生产:
Hello world