Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsafe template array constructor

Tags:

c++

This is probably a simple question but I have this template class:

template<typename Type>
class Array {
    size_t n;
    Type* buff;
public:
    Array(size_t n_): n(n_), buff(new Type[n]) {}
};

The code is from a course pdf file where it says buff(new Type[n]) is unsafe. I don't understand why it's unsafe, isn't size_t generally unsigned? Can I have an example where it could have a compile and/or run-time error?

like image 698
Loay Avatar asked Sep 07 '16 15:09

Loay


1 Answers

The code is "unsafe" in the fact that it relies on n being constructed before buff. This dependency adds brittleness to the code.

When you construct the members of the class they are constructed in the order the are declared in the class, not how they are called in the member initialization list, so if the code was changed to

template<typename Type>
class Array {
    Type* buff;
    size_t n;
public:
    Array(size_t n_): n(n_), buff(new Type[n]) {}
};

Then when you do buff(new Type[n]), n is uninitialized and you have undefined behavior.

like image 183
NathanOliver Avatar answered Oct 28 '22 09:10

NathanOliver