An array of one object

B

Bushido Hacks

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?
 
D

daya

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
 
B

Bushido Hacks

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
 
M

Marcus Kwok

Bushido Hacks said:
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.
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.
 
O

Old Wolf

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,144
Latest member
KetoBaseReviews
Top