Thread View: comp.std.c++
1 messages
1 total messages
Started by Mats Henricson
Tue, 16 Jan 1996 15:27
Re: can initialization be used with new[]?
Author: Mats Henricson
Date: Tue, 16 Jan 1996 15:27
Date: Tue, 16 Jan 1996 15:27
67 lines
2763 bytes
2763 bytes
In article <l8291j9wix9.fsf@neppari.cs.hut.fi>,
"Lassi A. Tuura" <Lassi.Tuura@hut.fi> writes:
>One compiler I need to use has problems with the following code:
>---------------
>#include <new.h>
>class T {
>public:
> T (int n) : _n (n) { }
> T (const T &ref) : _n (ref._n) { }
> ~T () { }
>
>private:
> int _n;
>};
>
>void f ()
>{
> T *ptr = new T [10] (1); // line 14
>}
>---------------
>
>In particular, it complains about the initializer to the vector new:
> CC: "test.cc", line 14: error: initializer for array of class object
> created using `new' (1248)
>
>Another compiler has no problems with the code, and the one giving the
>error message has not proved to be reliable. The question is: Is this
>legal C++? I read thru 5.3.4 from the april draft and as far as I
>understood the code was flagged ill-formed. Did I interpret the draft
>correctly? If I did, how am I supposed to allocate an array of
>objects of class T? With explicit calls to operator new and placement
>new?
The code is not legal. The reason is that the default constructor,
which is usually T::T(), will be used when you allocate arrays of T:s.
The compiler will generate a T::T() for you only in one case, namely
when you yourself have explicitly delared no other constructors. In
this case you have such a constructor, T::T(int n). Therefore the
compiler will not make a T::T() for you, which makes it impossible to
allocate arrays of T:s.
The fix is simple: Get yourself a T::T(). Another option is to give
the the int parameter a default value, usually 0 works OK. This would
give you this class:
class T
{
public:
T (int n = 0) : _n (n) { }
T (const T &ref) : _n (ref._n) { }
~T () { }
private:
int _n;
};
A side note: Don't use "_" as a prefix to identifiers, since that is
almost illegal according to the language. It is much better to use "_"
as a suffix.
Mats Henricson
Stockholm
Sweden
---
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads