Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect way to initialize dynamic Array in C++
    text
    copied!<p>I'm currently working on a C++ project, where dynamic arrays often appear. I was wondering, what could be the correct way to initialize a dynamic array using the new-operator? A colleague of mine told me that it's a no-no to use new within the constructor, since a constructor is a construct that shouldn't be prone to errors or shouldn't fail at all, respectively. Now let's consider the following example: We have two classes, a more or less complex class State and a class StateContainer, which should be self-explained.</p> <pre><code>class State { private: unsigned smth; public: State(); State( unsigned s ); }; class StateContainer { private: unsigned long nStates; State *states; public: StateContainer(); StateContainer( unsigned long n ); virtual ~StateContainer(); }; StateContainer::StateContainer() { nStates = SOME_DEFINE_N_STATES; states = new State[nStates]; if ( !states ) { // Error handling } } StateContainer::StateContainer( unsigned long n ) { nStates = n; try { states = new State[nStates] } catch ( std::bad_alloc &amp;e ) { // Error handling } } StateContainer::~StateContainer() { if ( states ) { delete[] states; states = 0; } } </code></pre> <p>Now actually, I have two questions:</p> <p>1.) Is it ok, to call new within a constructor, or is it better to create an extra init()-Method for the State-Array and why?</p> <p>2.) Whats the best way to check if new succeeded: </p> <pre><code>if (!ptr) std::cerr &lt;&lt; "new failed." </code></pre> <p>or</p> <pre><code>try { /*new*/ } catch (std::bad_alloc) { /*handling*/ } </code></pre> <p>3.) Ok its three questions ;o) Under the hood, new does some sort of </p> <pre><code>ptr = (Struct *)malloc(N*sizeof(Struct)); </code></pre> <p>And then call the constructor, right?</p>
 

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