Connecting Tech Pros Worldwide Forums | Help | Site Map

An array of one object

Bushido Hacks
Guest
 
Posts: n/a
#1: Mar 25 '07
When declaring a pointer to a single object in C++ the follwing code
is illegal:

Something* s;
s = new Something(); //ILLEGAL!
....
delete s;

The correct syntax is

Something* s;
s = new Something; //LEGAL
....
delete s;

Or if there is an argument

Something* s;
s = new Something(5.5); //LEGAL!
....
delete s;

When declaring a pointer to an array of objects, the following is
used.

Something* s;
s = new Something[3]; // LEGAL!
....
delete[] s;

What I would like to know is, is the following code legal?

Something* s;
s = new Something[1];
....
delete[] s;

Is is legal in C++ to create an array with just one object?


daya
Guest
 
Posts: n/a
#2: Mar 25 '07

re: An array of one object


the first example you mentioned

Something* s;
s = new Something(); //ILLEGAL!
....
delete s;


is in fact legal .and invokes the default constructor.....

and also it is legal to declare an array of 1 element...

Something* s;
s = new Something[1];
....
delete[] s;

is legal

Bushido Hacks
Guest
 
Posts: n/a
#3: Mar 25 '07

re: An array of one object


On Mar 25, 12:43 pm, "daya" <kdayan...@gmail.comwrote:
Quote:
the first example you mentioned
>
Something* s;
s = new Something(); //ILLEGAL!
...
delete s;
>
is in fact legal .and invokes the default constructor.....
>
and also it is legal to declare an array of 1 element...
>
Something* s;
s = new Something[1];
...
delete[] s;
>
is legal

thank you

Marcus Kwok
Guest
 
Posts: n/a
#4: Mar 26 '07

re: An array of one object


Bushido Hacks <bushidohacks@gmail.comwrote:
Quote:
When declaring a pointer to a single object in C++ the follwing code
is illegal:
>
Something* s;
s = new Something(); //ILLEGAL!
...
delete s;
It is actually legal. However, you may be thinking of the non-dynamic
allocation case:

Something s;

vs.

Something s();

Both of them are legal, but the first one defines an object named 's'
of type Something, whereas the second one declares a function named 's'
that takes no parameters and returns a Something.
Quote:
What I would like to know is, is the following code legal?
>
Something* s;
s = new Something[1];
...
delete[] s;
>
Is is legal in C++ to create an array with just one object?
Yes, it is perfectly legal.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Old Wolf
Guest
 
Posts: n/a
#5: Mar 28 '07

re: An array of one object


On Mar 26, 5:43 am, "daya" <kdayan...@gmail.comwrote:
Quote:
>
Something* s;
s = new Something(); //ILLEGAL!
delete s;
>
is in fact legal .and invokes the default constructor.....
If Something is POD then the code has a special meaning: with
the parentheses, the structure is zero-initialized. Without them,
the members have indeterminate value (i.e. uninitialized)

Closed Thread