Topic: Array element construction
Author: fjh@mundook.cs.mu.OZ.AU (Fergus Henderson)
Date: 1997/06/28 Raw View
ken@digitas.harvard.edu (Ken Shan) writes:
>The intent of the following code is to achieve individual
>initialization of array members. Is it guaranteed to work according
>to the current draft standard?
>
> struct T
> {
> int m_a;
> T(int a): m_a(a) { }
> };
>
> // ...
> {
> T *pt = reinterpret_cast<T*>(new char[sizeof(T) * 100]);
> // Side question: Should this be reinterpret_cast
> // or just static_cast?
> for (int i = 0; i < 100; ++i)
> new (pt + i) T(i);
> }
It should just be static_cast. Also, you should use `operator
new(sizeof(T) * 100)', not `new char [...]', because otherwise the
resulting pointer is not guaranteed to be properly aligned. Apart from
that, I think the code is fine.
--
Fergus Henderson <fjh@cs.mu.oz.au> | "I have always known that the pursuit
WWW: <http://www.cs.mu.oz.au/~fjh> | of excellence is a lethal habit"
PGP: finger fjh@128.250.37.3 | -- the last words of T. S. Garp.
---
[ 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 ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]
Author: ken@digitas.harvard.edu (Ken Shan)
Date: 1997/06/26 Raw View
Hello,
The intent of the following code is to achieve individual
initialization of array members. Is it guaranteed to work according
to the current draft standard?
struct T
{
int m_a;
T(int a): m_a(a) { }
};
// ...
{
T *pt = reinterpret_cast<T*>(new char[sizeof(T) * 100]);
// Side question: Should this be reinterpret_cast
// or just static_cast?
for (int i = 0; i < 100; ++i)
new (pt + i) T(i);
}
Thanks in advance...
--
Edit this signature at http://www.digitas.harvard.edu/cgi-bin/ken/sig
> > ERM failed. Fixed exchange rates are silly.
> (The first does not imply the second, you know).
Nevertheless, both are true.
---
[ 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 ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]