How to return a copy of data in C ++

I am trying to return a new copy of data to a C ++ template class. The following code gets this error: invalid conversion from 'int' to 'int*' . If I delete new T , then I will not return a copy of the data, but a pointer to it.

 template<class T> T OrderedList<T>::get( int k ) { Node<T>* n = list; for( int i = 0; i < k; i++ ) { n=n->get_link(); } return new T( n->get_data() ); // This line is getting the error ********** } 
+4
source share
1 answer

new creates and returns a pointer. You just need a copy that will be created implicitly, since the return statement will call the copy constructor (or equivalent for POD) of the T object:

 return n->get_data(); 
+11
source

Source: https://habr.com/ru/post/1304710/


All Articles