Deny std::vector from deleting its data

后端 未结 9 991
天涯浪人
天涯浪人 2021-01-17 11:03

I have the following case:

T* get_somthing(){
    std::vector vec; //T is trivally-copyable
    //fill vec
    T* temp = new T[vec.size()];
    memc         


        
9条回答
  •  庸人自扰
    2021-01-17 11:39

    Below is sample code how to do it with custom allocator. This assumes you can make vector actually use custom allocator. Also allocator uses static variable to control destruction of internal buffer. I have checked under VS2015 and its implementation calls deallocate in ~vector only for internal buffer - i.e. it does not manage any other allocations using this allocator.

    This is a hack - and I am not sure what consequences its use might have. Its not thread safe for sure (but could be easily fixed after making allow_dealloc thread local).:

    http://coliru.stacked-crooked.com/a/5d969a6934d88064

    #include 
    #include 
    #include 
    
    template 
    class my_alloc {
      std::allocator alloc;
    public:
      static bool allow_dealloc;
    
      typedef T        value_type;
      typedef T*       pointer;
      typedef const T* const_pointer;
      typedef T&       reference;
      typedef const T& const_reference;
      typedef std::size_t    size_type;
      typedef std::ptrdiff_t difference_type;
    
      pointer allocate(size_type num, const void* = 0) { return alloc.allocate(num);  }
      void deallocate(pointer p, size_type num) { 
          if (allow_dealloc) 
            alloc.deallocate(p, num*sizeof(T));  }
    
    
      // Squashed as less important
      template  struct rebind { typedef my_alloc other; };
      pointer address(reference value) const { return &value; }
      const_pointer address(const_reference value) const { return &value; }
      my_alloc() throw() { }
      my_alloc(const my_alloc&) throw() { }
      template  my_alloc(const my_alloc&) throw() { }
      ~my_alloc() throw() { }
      size_type max_size() const throw() { return (std::numeric_limits::max)() / sizeof(T); }  
      void construct(pointer p, const T& value) { alloc.construct(p, value); }
      void destroy(pointer p) { p->~T(); }  
    };
    
    template 
    bool my_alloc::allow_dealloc = true;
    
    int main()
    {
      int* data = 0;
      size_t size = 0;
      {
        my_alloc::allow_dealloc = true;      
        std::vector> vec= { 0, 1, 2, 3 };
        vec.push_back(4);
        vec.push_back(5);
        vec.push_back(6);
        my_alloc::allow_dealloc = false;
        data = vec.data();
        size = vec.size();
      }
    
      for (size_t n = 0; n < size; ++n)
        std::cout << data[n] << "\n";
    
      my_alloc alloc; 
      alloc.deallocate(data, size);
    }
    

提交回复
热议问题