Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this second new?

What is the second line? (Seen while answering another question.)

int * x = new int [1] ;
int * y = new (x) int;

After the second line x and y have the same value (point to a same place). What's the difference between y = x and the second line? Is it like a constructor or something?

like image 229
Amir Zadeh Avatar asked Oct 18 '10 15:10

Amir Zadeh


People also ask

What did the Second New Deal do?

It included programs to redistribute wealth, income, and power in favor of the poor, the old, farmers and labor unions. The most important programs included Social Security, the National Labor Relations Act ("Wagner Act"), the Banking Act of 1935, rural electrification, and breaking up utility holding companies.

Is there a Black Moon in 2022?

A Black Moon will appear for you on April 30, 2022, as the second new Moon in the month of April.

Why is the Moon yellow tonight 2022?

When the Moon is low on the horizon, you're looking through more of the atmosphere, and light has a longer distance to travel. Those colours with shorter wavelengths, like blue, get scattered leaving behind those colours with longer wavelengths like red, orange and yellow.

Who did the Second New Deal help?

Later, a second New Deal was to evolve; it included union protection programs, the Social Security Act, and programs to aid tenant farmers and migrant workers.


2 Answers

It's placement new. It constructs a new int in the memory pointed to by x.

If you try:

int * x = new int [1];
*x = 5;
std::cout << *x << std::endl;
int * y = new (x) int;
*y = 7;
std::cout << *x << std::endl;

the output will be:

5
7
like image 140
Oliver Charlesworth Avatar answered Oct 01 '22 23:10

Oliver Charlesworth


This is called placement new. It allows you to construct an object in memory already allocated.

This earlier thread discusses where and how it is useful for.

like image 39
Péter Török Avatar answered Oct 01 '22 22:10

Péter Török