Salt_Peter
11/2/2008 2:13:00 AM
On Nov 1, 6:57 pm, aaragon <alejandro.ara...@gmail.com> wrote:
> Hello everyone,
>
> Is this valid?
>
> template <class A>
> struct ClassA {
>
> typedef A value_type;
> value_type* data_;
// if its a pointer, label it as such
value_type* p_data;
>
> explicit ClassA(size_t n) : data(new value_type[]()) {} // note
> the () after []
>
// all elements of an array are default constructed.
// in fact, if a default ctor is not available for
// that template parameter, you lose
explicit ClassA(const std::size_t n)
: p_data(new value_type[n]) { }
~ClassA() { delete [] p_data; }
> // other stuff
>
> };
>
> Here A is any type, including primitive types. I run valgrind on this
> code and it gives me the "Conditional jump or move depends on
> uninitialised value(s)" error. So if it is not valid, why is it? Is
> there a way to default initialize the array in the initialization
> list?
>
> Thank you all,
>
> aa
A much better solution is to use a std::vector<>, where elements are
stored in contiguous memory like an array. Another container that is a
workhoerse is std::deque<>, elements are not contiguous. Advantages
imclude that these containers are dynamic / resizeable, allocate and
deallocate automatically. Blends very nicely with common algorithms
(random access iterator, begin/end). It has a common interface. Very
powerfull and a LOT easier to use. Its elements need not have a
default ctor:
class E { explicit E(double n) { } };
std::vector< E > vd(1000, E(99.9));
On the other hand, if i were to reinvent the wheel, I'ld design a
fixed array with a const size_t as a template parameter.
template< class A, const std::size_t Size >
struct Array
{
typedef A value_type;
// ctors
Array() : data() {}
explicit Array(const A& a)
{
for(value_type* pv = &data[0]; pv != &data[Size]; ++pv)
{
*pv = a;
}
}
// and so on ...
private:
value_type data[Size];
};