Search code examples
c++vectorshared-ptr

Making a pair of shared pointer and pushing in a vector


I am trying to make a pair of shared pointer and push it into a list and get an error. The error is at the line list_of_objects_combination.push_back()

What is wrong in my code?

no matching function for call to ‘Objects::Objects(__gnu_cxx::__normal_iterator*, std::vector > >&)’ { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

void MyClass::getCombination(std::vector<std::shared_ptr< Objects>> m_list_objects,
                                 std::vector<std::pair<std::shared_ptr<Objects>, std::shared_ptr<Objects>>> &list_of_objects_combination) {

    std::vector<std::shared_ptr< Objects>>::const_iterator objectIterator = m_list_objects.begin();
    std::vector<std::shared_ptr<Objects>>::const_iterator objectIteratorNext;

    for (; objectIterator < m_list_objects.end(); objectIterator++) {
        for (objectIteratorNext = objectIterator + 1; objectIteratorNext < m_list_objects.end();
             objectIteratorNext++) {

            list_of_objects_combination.push_back(std::make_pair(std::make_shared<Objects>(objectIterator),
                                                                 std::make_shared<Objects>(objectIteratorNext)));
        }
    }
}

Solution

  • You are trying to make a pair from vector iterators: std::make_shared<Objects>(objectIterator), instead of Objects/shared_ptrs. Try std::make_pair(*objectIterator, *objectIteratorNext). That way you'll avoid another bug in your code, since you were trying to make new shared_ptr to existing objects, instead of copying existing ones. Currently, even std::make_shared<Objects>(objectIterator) to std::make_shared<Objects>(objectIterator->get()) that'll create new shared_ptrs with separate ref counts which would lead to double deleting/UB.