Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a copy of the data in C++

Tags:

c++

pointers

I am trying to return a new copy of the data in a C++ Template class. The following code is getting this error: invalid conversion from 'int' to 'int*'. If I remove the new T then I am not returning 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 **********
}
like image 275
Josh Curren Avatar asked Dec 22 '22 04:12

Josh Curren


1 Answers

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

return n->get_data();
like image 126
Konrad Rudolph Avatar answered Dec 29 '22 00:12

Konrad Rudolph