Вопрос

The following code produces a segmentation fault and I don't know why:

    myTree<int> tree;
    tree.insert(10); // not important

    std::vector<int> v = tree.toVector(); // Segmentation fault

This is the myTree code (reduced, not compilable, just enough to understand what it's about):

template<class T> struct node {
    T key;
    node *left;
    node *right;
    int count;

    node(const T &k=T(), node *l=0, node *r=0) {
        key = k;
        left = l;
        right = r;
        count = 1;
    }
};

template<class T> class myTree {
public:
    myTree() {
        root = 0;
    }

    void traverseInOrder(void (*visitFunc)(node<T>* n)) {
        traverseInOrder(visitFunc, root);
    }

    std::vector<T> toVector() {
        std::vector<T> v;
        traverseInOrder([&](node<T>* n) {
            v.insert(v.end(), n->count, n->key);
        });
        return v;
    }
private:
    void traverseInOrder(void (*visitFunc)(node<T> *n), node<T> *n) {
        if (n == 0) {
            return;
        } else {
            if (n->left != 0) {
                traverseInOrder(visitFunc, n->left);
            }

            (*visitFunc)(n);

            traverseInOrder(visitFunc, n->right);
        }
    }

    node<T> *root;
};

The segmentation fault occurs in this line:

v.insert(v.end(), n->count, n->key);

The NetBeans variables window says v is OUT_OF_SCOPE.

Question: Am I using the lambda correctly?

Note: I am using g++ (GCC) 4.7.2 (Cygwin).

Это было полезно?

Решение

As mentioned by @Arkadiy in the comments, a stateful lambda does not decay to a function pointer. The fix is to write your traverseInOrder as a template that takes a callable object

template<class Func>
void traverseInOrder(Func visitFunc)) {
    traverseInOrder(visitFunc, root);
}

Alternatively, you could be more type-safe and give it a signature that takes a std::function that returns void and takes a node<T>*

void traverseInOrder(std::function<void(node<T>*)> visitFunc)) {
    traverseInOrder(visitFunc, root);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top