class B;
class A {
B *b;
public:
A(B *p) : b(p) {}
};
class B {
public:
void foo() {
// this declaration is ok
A a(this);
// the following causes an error with newer GCC:
// error: ISO C++ forbids initialization in array new
A *arr = new A[10](this);
}
};
int main()
{
B b;
}
This worked with g++ until version 3.3.x, but not since 3.4.x. The
problem is in the expression new A[10](this), since according to GCC,
initialization in array new is forbidden.
How would I initialize the array elements in ISO C++?
urs
There is no way to specify constructor arguments when using the array
version of new. The default constructor must be available.
Please see the older thread
http://groups.google.co.uk/group/comp.lang.c++.moderated/browse_frm/thread/18f1c9313d32d315
for more information.
--
Max
> class B;
> class A {
> B *b;
> public:
> A(B *p) : b(p) {}
> };
> int main()
> {
> B b;
> }
It's always been forbidden.
> How would I initialize the array elements in ISO C++?
std::vector< A > v( 10, this ) ;
--
James Kanze (GABI Software) email:james...@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
That is, of course, the best and safest way of doing it.
OTOH, it might be interesting to know how std::vector does this.
(After all, std::vector *does* allocate space for a certain amount of
elements without needing a default constructor for those elements.) It
goes something like this:
// Requires #include <memory>
A* array = std::allocator<A>().allocate(10);
for(int i = 0; i < 10; ++i)
new(array+i) A(this);
Of course I'm not recommending you to do it like this. Use std::vector
instead.
No magic here: allocate raw memory and then invoke the constructors
manually.
std::uninitialized_fill() is used in some std::vector<>
implementations for the second step. http://www.sgi.com/tech/stl/uninitialized_fill.html
--
Max