Search code examples
c++listpointersstdlist

Copy list of pointers no loops


i have a list with pointers to some Object. i want to copy the list but with new pointers.

i mean every element in list , to do new to object and insert the new adress in new list.

i try to use with:

 std::list<Course*> tmp;

 tmp = courses; // courses is list<Course*>.

 std::for_each(tmp.begin(), tmp.end(), ReplaceAllCells());



class ReplaceAllCells {
public:
    ReplaceAllCells(){}
     void operator( )( Course* course) {
         course = new Course(*course);
    }
};

after the call to function i get new list with same pointers... the value of tmp no changed.. How can i fix that without use any loops? thanks.


Solution

  • Function arguments are passed by value in C, if you don't use a reference type. When you have:

    void f(T t)
    {
         t = something.....
    }
    

    this only affects the local copy t, not the variable that was given as argument to this function call. Whether or not T is a pointer type makes no difference

    You need to accept the argument by reference if you want to modify it, T &t here, or in your case Course * &course.