Reputation: 4124
I have a constructor which create and empty A with r rows and c columns
A::A(int r, int c)
: row(r), column(c), e(new int[r*c])
{
for (int i = 0; i < r*c; i++)
{
e[i] = 0;
}
}
I am wondering if a memory allocation will failed, it will still initialize row and column with non-zero values. How can I prevent it ?
Upvotes: 1
Views: 161
Reputation: 50061
If new
fails to allocate memory, it throws an instance of std::bad_alloc
, i.e. an exception.
If your constructor fails, all already completely constructed members and bases are destroyed and no valid instance of your type is created.
So your r
and c
have no value at all if you leave your constructor via an exception because they do not exist.
You will indeed never even reach the loop you seem to worry about.
Upvotes: 9