HahaHortness
HahaHortness

Reputation: 1628

Infinite recursion in copy constructor

I'm having trouble in a part of my program where I pass an object that acts as a lambda function to another function (I need to capture a const this pointer so I can't use an actual lambda). This causes the copy constructor of my lambda to be called, which again calls the copy constructor, and eventually the stack overflows. I understand what's happening but I'm not sure why the copy constructor is calling itself or how to fix this. I've reproduced the problem below.

Compiler: MSVC 2010

#include <functional>

void synchronizedExecution(std::function<void()> function) {
    function();
}

int main(int argc, char *argv[])
{

    int b = 0;

    class Function : public std::function<void()> {
    public:
        int& b;
        Function(int& b) :
            b(b) {}
        void operator()() {}
    } function(b);

    synchronizedExecution(function);

    return 0;
}

Upvotes: 1

Views: 974

Answers (2)

Michael Simbirsky
Michael Simbirsky

Reputation: 3103

First, to solve your problem you can probably pass object by reference, not by value.

Second, your coding is very prone to errors. When you introduce a new name and it is the same as the existing one, you have a collision which compiler solves but you not always get what you expected. For example

   class Function
        int& b;
        Function(int& b) :
            b(b) {}

I am honestly not sure, which b will be substituted into (), the class member or the function parameter. AFAIR, the class member has precedence and this is not what you intended. I suspect your actual problem has the same cause.

Upvotes: 0

PaF
PaF

Reputation: 3477

I can help you with the "how to fix this" part - change your function to

void synchronizedExecution(const std::function<void()>& function)

Upvotes: 3

Related Questions