S
S
solaris2012-11-08 15:32:12
C++ / C#
solaris, 2012-11-08 15:32:12

Is there an STL wrapper for a raw memory buffer?

There is this bike:

#include <memory>
#include <iostream>

class memory_block {
 public:
  memory_block(std::size_t size) {
    init(size);
  };

  memory_block(const memory_block &src) {
    *this = src;
  };

  memory_block& operator=(const memory_block &src) {
    init(src.real_size_);
    std::copy(src.start(), src.end(), start());
    return *this;
  };

  ~memory_block() {
    clear();
  };

  char* start() const {
    return internal_ptr_.first;
  };

  char* end() const {
    return internal_ptr_.first + internal_ptr_.second;
  };

 private:
  void clear() {
    std::return_temporary_buffer(internal_ptr_.first);
  };

  void init(std::size_t size) {
    if (size > real_size_) {
      clear();
      real_size_ = size;
    }
    this->internal_ptr_ = std::get_temporary_buffer<char>(size);
  };

  std::pair<char*, std::ptrdiff_t> internal_ptr_;
  size_t real_size_;
};

int main(int argc, char *argv[]) {
  char test_str[] = "123456789";
  memory_block b1(10);
  std::copy(test_str, test_str + 10, b1.start());
  memory_block b2(b1);
  memory_block b3(0);
  memory_block b4(0);
  b3 = b1;
  std::cout << b1.start() << std::endl; // "123456789"
  std::cout << b2.start() << std::endl; // "123456789"
  std::cout << b3.start() << std::endl; // "123456789"
  std::cout << std::boolalpha;
  std::cout << (b4.start() == NULL) << std::endl; // true
  std::cout << (b4.end() == NULL) << std::endl; // true
  return 0;
}


Are there any standard buns that allow him to be thrown out of the project? There is one unpleasant "but" - the compiler, C ++ Builder5 . I googled boost::asio::buffer, but unfortunately boost doesn't work with this miracle builder. I did not find anything similar in STL. There is an option to use std::vector, which supposedly guarantees continuity, but it seems to me a worse hack than the current one. Maybe I overlooked something?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ixSci, 2012-11-08
@solaris

Yes, you overlooked:
First:

which supposedly guarantees the continuity

not supposedly, but guaranteed.
First: This is not a hack, but a normal use of a dynamically expandable buffer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question