Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alloc memory in constructor or init function?

I'm new to C++, I have a class hold some memory, the class looks like:

class MyClass
{
public:
    MyClass (int s)
    {
        if (s <= 0) _size = 1;
        else _size = s;

        data = new int[_size];  // may throw exception
    }


private:
    int *data;
    int _size;
};

To my knowledge, throw exception in constructor is unsafe, so I put the malloc to a init function.


class MyClass
{
public:
    MyClass (int s)
    {
        if (s <= 0) _size = 1;
        else _size = s;
    }

    void init()
    {
        data = new int[_size];
    }


private:
    int *data;
    int _size;
};

my problem:

  1. memory alloc in constructor or init function, which is better
  2. if I chose init function, how to ensure init function has called before call other member function?
like image 621
dancedpipi Avatar asked Dec 31 '22 14:12

dancedpipi


1 Answers

To my knowledge, throw exception in constructor is unsafe, so I put the malloc to a init function.

No, it is not "unsafe". It's the way to fail a constructor. You may be thinking about destructors aborting or other issues with exception safety guarantees.

"Init" functions introduce a two phase approach to constructors that increases complexity. Unless you need to work in an environment without exceptions, avoid them. Factory functions are another way to do things in that case.

memory alloc in constructor or init function, which is better

Constructor. See std::vector.

if I chose init function, how to ensure init function has called before call other member function?

Statically you cannot without a run time check or external tools.

You can set a flag on your init function and then check in every member function.

like image 129
Acorn Avatar answered Jan 02 '23 04:01

Acorn