NEURON
unique_cstr.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include <cstdlib>
4 #include <utility>
5 #include <ostream>
6 
8 
9 namespace neuron {
10 
11 /** A RAII wrapper for C-style strings.
12  *
13  * The string must be null-terminated and allocated with `malloc`. The lifetime of the string is
14  * bound to the life time of the `unique_cstr`. Certain patterns in NRN require passing on
15  * ownership, this is achieved using `.release()`, which returns the contained C-string and makes
16  * this object invalid.
17  */
19  public:
20  unique_cstr() = default;
21  unique_cstr(const unique_cstr&) = delete;
22  unique_cstr(unique_cstr&& other) noexcept {
23  *this = std::move(other);
24  }
25 
26  unique_cstr& operator=(const unique_cstr&) = delete;
27  unique_cstr& operator=(unique_cstr&& other) noexcept {
28  std::free(this->str_);
29  this->str_ = std::exchange(other.str_, nullptr);
30  return *this;
31  }
32 
33  explicit unique_cstr(char* cstr)
34  : str_(cstr) {}
35 
37  std::free((void*) str_);
38  }
39 
40  /** Releases ownership of the string.
41  *
42  * Returns the string and makes this object invalid.
43  */
44  [[nodiscard]] char* release() {
45  return std::exchange(str_, nullptr);
46  }
47 
48  char* c_str() const {
49  return str_;
50  }
51  bool is_valid() const {
52  return str_ != nullptr;
53  }
54 
55  private:
56  char* str_ = nullptr;
57 };
58 
59 } // namespace neuron
A RAII wrapper for C-style strings.
Definition: unique_cstr.hpp:18
char * release()
Releases ownership of the string.
Definition: unique_cstr.hpp:44
unique_cstr(const unique_cstr &)=delete
char * c_str() const
Definition: unique_cstr.hpp:48
unique_cstr & operator=(unique_cstr &&other) noexcept
Definition: unique_cstr.hpp:27
bool is_valid() const
Definition: unique_cstr.hpp:51
unique_cstr(char *cstr)
Definition: unique_cstr.hpp:33
unique_cstr(unique_cstr &&other) noexcept
Definition: unique_cstr.hpp:22
unique_cstr & operator=(const unique_cstr &)=delete
void move(Item *q1, Item *q2, Item *q3)
Definition: list.cpp:200
In mechanism libraries, cannot use auto const token = nrn_ensure_model_data_are_sorted(); because the...
Definition: tnode.hpp:17
#define NRN_EXPORT
Definition: nrn_export.hpp:6