make_shared 与自定义 new 运算符

2024-02-23

这可能是重复的,但我无法在任何地方找到解决方案。

我有这样的源代码:

struct Blob{
    //...    

    static void *operator new(size_t size_reported, size_t size) {
        return ::operator new(size);
    }
};

我这样使用它:

std::shared_ptr<Blob> blob;
// ...
size_t size = calcSize(); // it returns say 231
Blob *p = new(size) Blob();
blob.reset(p);

我可以以某种方式更改代码以便我可以使用std::make_shared or std::allocate_shared所以我有single allocation代替two allocations?


Update

我能够消除new并将代码简化为以下内容:

struct Blob{
    //...    
};

std::shared_ptr<Blob> blob;
// ...
size_t size = calcSize(); // it returns say 231

// allocate memory
void *addr = ::operator new(size);

// placement new
Blob *p = ::new(addr) Blob();

blob.reset(p);

它做了完全相同的事情,但我想现在我想做什么更清楚了。


这是我们的想法。

由于无法将大小传递给分配器,因此您可以通过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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

make_shared 与自定义 new 运算符 的相关文章

随机推荐