0

I am a hobbyist programmer and a little knowledge is a dangerous thing. I wanted to include a user defined compare function into my class (e.g. std::less). So, I wrote a test program:

#include "pch.h"
#include <iostream>
#include <functional>


bool myfunc(const int& a, const int& b) {
    return a < b;
}

template <class K>
class myclass
{
public:
    myclass(const std::function<bool(const K&, const K&)>& fn);
    const std::function<bool(const K&, const K&)>& comp;
};

template <class K>
myclass<K>::myclass(const std::function<bool(const K&, const K&)>& fn) : comp(fn)
{

}

using std::cout;

int main()
{
    myclass<int> foo(myfunc);
    cout << std::boolalpha << myfunc(1, 2) << "\n";
    cout << std::boolalpha << foo.comp(1, 2) << "\n";
    cout << "Hello World!\n"; 
}

The program compiles. myfunc works as expected. However, I got the following run-time error message:

Exception thrown at 0x75BAB022 in forward.exe: Microsoft C++ exception: std::bad_function_call at memory location 0x00B4F5F4.
Unhandled exception at 0x75BAB022 in forward.exe: Microsoft C++ exception: std::bad_function_call at memory location 0x00B4F5F4.

Yes, I have searched for answers, no I have not found something that I understand. Any help would be appreciated. (Written in VS17, with c++17 turned on.)

davidbear
  • 375
  • 2
  • 13
  • 2
    `myclass foo(myfunc)` creates a temporary function object that `comp` refers to. That goes out of scope at the end of the declaration statement and is destroyed, leaving `comp` as a dangling reference. Change `comp` from a reference to a non-reference (to keep a copy of the function object). – 1201ProgramAlarm Mar 10 '19 at 02:39
  • You have a dangling reference problem. `myclass foo(myfunc);` creates a temporary `std::function` object which is destroyed after the line is executed. – R Sahu Mar 10 '19 at 02:39

0 Answers0