Copying a std::function object to another std::function
I have the following declaration of a binary search tree: template<class Type, class Predicate = std::less<Type>> binary_search_tree; In this class, along with a root node, I store a std::function object to be used as the comparison predicate during insert operations. I now had to make a function to generate the mirror image of a binary_search_tree object. In the function implemented for the same, after performing the required operations, I assign a new comparison predicate to the mirrored object: mirror_bst.compare = [this](value_type v1, value_type v2)->bool{ return !this->compare(v1,v2); }; Now, when I try to copy the returned object to a newly created object, the program crashes. Backtracing in GDB shows a SIGSEGV raised in the following call: 0x0000000000404ba0 in std::function<bool (int, int)>::operator()(int, int) const ( __args#1=<optimized out>, __args#0=<optimized out>, this=<optimized out>) The copy constructor is defined in the following way: binary_search_tree(const binary_search_tree& bst) : binary_search_tree() { compare = bst.compare; bst.traverse_preorder([this](const vertex& node){ this->insert(*node); }); } A move constructor is also defined in the class: binary_search_tree(binary_search_tree&& bst) : binary_search_tree() { compare=std::move(bst.compare); root=bst.root; csize=bst.csize; bst.csize=0; bst.root=bst.end_iter; } When the returned object is moved instead of copied, the program works as expected. Why? Also, if the following line: compare = bst.compare; is commented, the program executes successfully but displays incorrect results due to an incorrect predicate. Why does the program not crash in this case? Link to the complete code: https://code.sololearn.com/cDe9SPnEH3T1/#cpp