Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decltype a dereferenced pointer in C++ [duplicate]

Can somebody explain to me why I can't do something along the lines of:

int* b = new int(5);
int* c = new decltype(*b)(5);

cout << *c << endl;

This throws C464 'int &': cannot use 'new' to allocate a reference. How would I perform doing something like this? What I need is the derefferenced base type of the variable that I send.

This works though

int* b = new int(5);
int** a = new int*(b);

decltype(*a) c = *a;
cout << *c<< endl;

I understand how the code above works but how would I perform something like that using new?

like image 390
Ilhan Karić Avatar asked Dec 11 '15 19:12

Ilhan Karić


1 Answers

The dereference operator * returns a reference, which you cannot allocate using new. Instead you could use std::remove_pointer in <type_traits>

int* b = new int(5);
int* c = new std::remove_pointer<decltype(b)>::type(5);    
std::cout << *c << std::endl;
like image 126
Cory Kramer Avatar answered Nov 19 '22 09:11

Cory Kramer