Created
January 17, 2016 18:41
-
-
Save conioh/28742c38b753c5301d5d to your computer and use it in GitHub Desktop.
Construction-free allocator for C++ standard library containers
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
// Originally written by https://github.com/kobykahane | |
#include <string> | |
#include <vector> | |
#include <memory> | |
#include <utility> | |
#include <Windows.h> | |
template <typename T> class no_construct_allocator : public std::allocator<T> | |
{ | |
public: | |
no_construct_allocator() {} | |
template <typename U> no_construct_allocator(const no_construct_allocator<U>& other) {} | |
template <typename U> struct rebind { typedef no_construct_allocator<U> other; }; | |
template <typename U, typename... Args> void construct(U* p, Args&&... args) | |
{ | |
// Needed for other stuff that's constructed with this allocator like the container proxy object used by vector iterators in debug. | |
::new ((void*)p) U(std::forward<Args>(args)...); | |
} | |
void construct(wchar_t* p) | |
{ | |
// Do nothing for default constructed wchar_t. | |
} | |
}; | |
template <typename T> using no_construct_vector = std::vector<T, no_construct_allocator<T>>; | |
int main() | |
{ | |
no_construct_vector<wchar_t> buf(5000); | |
GetEnvironmentVariable(L"PATH", buf.data(), static_cast<DWORD>(buf.size())); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment