Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is an attempt at an RAII class that does something similar:</p> <pre><code>template&lt;std::size_t N&gt; class StringGetter_N { private: std::unique_ptr&lt;char[]&gt; buffer; public: StringGetter_N() { buffer.reset( new char[N] ); buffer.get()[0] = 0; } explicit StringGetter_N(char const* name) { buffer.reset( new char[N] ); strcpy_s(buffer.get(), N-1, name); buffer.get()[N-1] = 0; // always null terminate } StringGetter_N( StringGetter_N&amp;&amp; other ) = default; char* GetString() { return buffer.get(); } }; class StringGetter : StringGetter_N&lt;1024&gt; { explicit StringGetter( const char* name ):StringGetter_N&lt;1024&gt;(name) {} StringGetter():StringGetter_N&lt;1024&gt;() {} }; </code></pre> <p>notice that I delegated the resource management to a smart pointer. Single responsibility principle means that the resource management object (like a smart pointer) can do just that, and if you want to write a class that represents a heap-allocated buffer of fixed size, you delegate that sub problem to the smart pointer, and just manage it in your class.</p> <p>As it happens, <code>std::unique_ptr</code> properly implements </p> <p>But really, it is usually much simpler to just use a <code>std::vector</code>, as you can usually determine how much space you need at run-time before needing a buffer to write to.</p> <p>If you do implement your own RAII class, you should follow these rules:</p> <ul> <li>Single argument constructors that are not copy/move constructors should usually be <code>explicit</code>.</li> <li>If you implement a non-trivial destructor, you must (implement or block usage of) (copy and/or move constructor) and (copy and/or move operator=). This is known as the rule of 3 (or rule of 5 in C++11).</li> <li>Your RAII class should do little except manage the resource. If you want to do something else, use an RAII class to manage the resource, then store it within another class that does the fancy extra work.</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload