这是我们的想法。
由于无法将大小传递给分配器,因此您可以通过global variable
or class member
.
在这两种情况下,解决方案一点也不优雅,而且相当危险——当代码需要维护时,灾难现在或以后就会发生。
如果出现以下情况,可能会出现另一个意想不到的问题:allocate_shared
放置shared_ptr
控制块after缓冲区类。
在这种情况下,将会出现明显的缓冲区溢出,因为sizeof(buffer)
将报告大小,如 1 字节左右。
再一次 - 代码可以工作,但将来肯定会出现问题。
#include <stdio.h>
#include <string.h>
#include <memory>
// ============================
class buffer{
public:
buffer(const char *s){
strcpy(x, s);
}
char x[1];
};
// ============================
template <typename T>
struct buffer_allocator {
using value_type = T;
buffer_allocator() = default;
template <class U>
buffer_allocator(const buffer_allocator<U>&) {}
T* allocate(size_t n) {
void *p = operator new(n * sizeof(T));
printf("Allocate %p, (%zu)\n", p, get_size());
return (T*) p;
}
void deallocate(T* p, size_t n) {
delete p;
printf("Deallocate %p, (%zu)\n", p, get_size());
}
size_t get_size(){
return size;
}
void set_size(size_t size){
this->size = size;
}
private:
size_t size = 0;
};
template <typename T, typename U>
inline bool operator == (const buffer_allocator<T>&, const buffer_allocator<U>&) {
return true;
}
template <typename T, typename U>
inline bool operator != (const buffer_allocator<T>& a, const buffer_allocator<U>& b) {
return !(a == b);
}
// ============================
int main(int argc, char *argv[]){
buffer_allocator<buffer> ba;
const char *s = "hello world!";
ba.set_size( strlen(s) + 1 );
auto b = std::allocate_shared<buffer>(ba, s);
printf("Pointer %p\n", b.get());
printf("%s\n", b->x);
printf("%zu\n", b.use_count());
auto b1 = b;
printf("%zu\n", b1.use_count());
return 0;
}