Re: What's the latest on initialising arrays?
Frederick Gotham <fgothamNO@SPAM.com> wrote:
What's the latest on adding array initialisation functionality to the
language? The following doesn't work if T doesn't have a public copy
constructor:
T array[] = { T(1), T(2), T(3), T(4), T(5) };
Here's some code I wrote today which initialises array members differently
-- I think you'll agree that it's unnecessarily complicated:
#include <new>
#include <iostream>
using std::cout;
#include <boost/type_traits/aligned_storage.hpp>
#include <boost/type_traits/alignment_of.hpp>
using boost::alignment_of;
using boost::aligned_storage;
class MyClass {
private:
int *const p;
MyClass(MyClass const &); /* Can't copy-construct! */
public:
MyClass(char const*) : p(new int)
{
cout << "Constructing!\n";
}
~MyClass()
{
delete p;
cout << "Destructing!\n";
}
};
int main()
{
aligned_storage<sizeof(MyClass)*5,
alignment_of<MyClass>::value> mem;
{
MyClass *p = reinterpret_cast<MyClass*>(&mem);
::new(p++) MyClass("a");
::new(p++) MyClass("b");
::new(p++) MyClass("c");
::new(p++) MyClass("d");
::new(p++) MyClass("e");
}
{
MyClass *p = reinterpret_cast<MyClass*>(&mem);
p++->~MyClass();
p++->~MyClass();
p++->~MyClass();
p++->~MyClass();
p++->~MyClass();
}
}
Considering all the functionality and features C++ has, this seems to be
quite a shortcoming.
Well this looks like it does the same thing and the same assumptions
as above and less tedious...
// create a fixed array of non_copyable objects.
template <class T,size_t N>
class Array
{
aligned_storage<sizeof(T)*N,alignment_of<T>::value >::type buffer;
T *p_T;
public:
template <class In>
Array(In bwgin)
{
p_T = reinterpret_cast<T *>(&buffer);
for(T *p=p_T;p!=p_T+N,++p,++begin)
::new(p) T(*begin);
}
~Array()
{
for(T *p=p_T;p!=p_T+N;++p)
p->~T();
}
T & operator [] (int n) {return p_T[n];}
};
// example.
int main()
{
const char **p = {"a","b","c","d","e";}
Array<MyClass,5> array(p);
}
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]