Skip to content

Instantly share code, notes, and snippets.

@jmarantz
Last active May 15, 2019 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmarantz/bfc3395dfc8b8e0c8c64ffa2af96b53e to your computer and use it in GitHub Desktop.
Save jmarantz/bfc3395dfc8b8e0c8c64ffa2af96b53e to your computer and use it in GitHub Desktop.
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
class InlineStorage {
public:
// Custom delete operator to keep C++14 from using the global operator delete(void*, size_t),
// which would result in the compiler error:
// "exception cleanup for this placement new selects non-placement operator delete"
static void operator delete(void* address) {
std::cout << "Deleting " << address << std::endl;
::operator delete(address);
}
protected:
static void* operator new(size_t object_size, size_t data_size) {
void* p = ::operator new(object_size + data_size);
std::cout << "Allocating " << (object_size + data_size) << " bytes --> " << p << std::endl;
return p;
}
};
class MyString : public InlineStorage {
public:
static MyString* create(const std::string& str) {
return new (str.size()) MyString(str.data(), str.size());
}
std::string toString() const { return std::string(data_, size_); }
size_t size() const { return size_; }
const char* data() const { return data_; }
private:
MyString(const char* str, size_t size) : size_(size) {
memcpy(data_, str, size);
}
size_t size_;
char data_[];
};
int main() {
std::unique_ptr<MyString> str(MyString::create("Hello, world!"));
std::cout << "str=" << str->toString() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment