Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef CSTRING_VECTOR_HPP
- #define CSTRING_VECTOR_HPP
- #include <algorithm>
- #include <iterator>
- #include <string>
- #include <vector>
- namespace utility {
- /// This is like vector<string> except with a C-friendly API. Or you can
- /// think of it as like vector<char const*> except it automatically
- /// cleans up its pointers.
- //
- // Inspired by http://forums.xkcd.com/viewtopic.php?p=3029979#p3029979
- class cstring_vector
- {
- /// This vector manages the lifetimes and automatic deletions of the
- /// strings themselves.
- std::vector<std::string> std_string_buffer;
- /// This vector provides a view of std_string_buffer that's
- /// C-compatible
- std::vector<char const *> cstring_buffer;
- /// This sets up the cstring_buffer to mirror std_string_buffer. This
- /// needs to be done after any of the std_string_buffer strings are
- /// changed. In the public API of this class, that means only after
- /// init.alization
- void make_c_buffer()
- {
- std::transform(std_string_buffer.begin(),
- std_string_buffer.end(),
- std::inserter(cstring_buffer, cstring_buffer.begin()),
- [](std::string const & str) {
- return str.c_str();
- });
- cstring_buffer.push_back(nullptr);
- }
- public:
- ///
- /// Constructs this cstring_vector with a copy of 'orig'
- cstring_vector(std::vector<std::string> orig)
- : std_string_buffer(orig)
- {
- make_c_buffer();
- }
- /// Copies the given cstring_vector. The copy gets a new copy of all
- /// the strings, and they will be located at a new place in memory.
- cstring_vector(cstring_vector const & other )
- : std_string_buffer( other.std_string_buffer)
- {
- make_c_buffer();
- }
- ///
- /// Move constructor; sets this to be 'other' and destroys 'other'.
- cstring_vector(cstring_vector && other )
- : std_string_buffer(std::move(other.std_string_buffer))
- , cstring_buffer(std::move(other.cstring_buffer))
- {}
- /// Returns a C-compatible view into this buffer, as a null-terminated
- /// array of char const * strings.
- char const * const *
- get_c_buffer() const
- {
- return &cstring_buffer.front();
- }
- /// Returns a C-compatible view into this buffer, as a null-terminated
- /// array of char const * strings.
- char const * *
- get_c_buffer()
- {
- return &cstring_buffer.front();
- }
- /// Returns the number of strings in the array (not counting the final
- /// terminating NULL).
- size_t count_strings() const
- {
- return std_string_buffer.size();
- }
- };
- }
- // Yo, Emacs!
- // Local Variables:
- // c-file-style: "ellemtel"
- // c-basic-offset: 4
- // indent-tabs-mode: nil
- // End:
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement