Last active
May 15, 2019 23:44
-
-
Save jmarantz/bfc3395dfc8b8e0c8c64ffa2af96b53e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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