new operator - difference in usage?

W

WittyGuy

Is there any difference between the following two snippets of code?

snippet1:
int main()
{
int* p = new int(5); // With argument for initialising p to the
value 5
....
....
....
delete p;
return 0;
}

snippet2:

int main()
{
int* p = new int; // Simply allocate memory in free store for p
*p = 5;
....
....
....
delete p;
return 0;
}

thanks,
--Wg-
 
N

n2xssvv g02gfr12930

WittyGuy said:
Is there any difference between the following two snippets of code?

snippet1:
int main()
{
int* p = new int(5); // With argument for initialising p to the
value 5
....
....
....
delete p;
return 0;
}

snippet2:

int main()
{
int* p = new int; // Simply allocate memory in free store for p
*p = 5;
....
....
....
delete p;
return 0;
}

thanks,
--Wg-

Functionally no. Which form you prefer is up to you, personally I prefer
the first because it tends to be more universal when using objects.

JB
 
R

Richard Herring

Is there any difference between the following two snippets of code?

snippet1:
int main()
{
int* p = new int(5); // With argument for initialising p to the
value 5
....
....
....
delete p;
return 0;
}

snippet2:

int main()
{
int* p = new int; // Simply allocate memory in free store for p
*p = 5;
....
....
....
delete p;
return 0;
}
For primitive types like int, there's no observable difference.

For class types, the effects may be different, because the first invokes
the copy constructor, the second uses the default constructor followed
by the assignment operator.
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top