mercredi 6 avril 2016

Callback pattern with a Functor

I'm trying to wrap an HttpRequest object (from Cocos2d-x) in my own functor. Everything's working fine except calling the callback passed to my functor. Can you spot the error in the classes below? (I only pasted the relevant parts of the code).

Cloud.hpp:

#ifndef Cloud_hpp
#define Cloud_hpp

#include "external/json/document.h"
#include "network/HttpClient.h"

using namespace cocos2d::network;

typedef std::function<void()> CloudCallback;

class Cloud
{
private:
    std::string url { "http://localhost:3000/1.0/" };
    std::string end_point;
    CloudCallback callback;

    std::string getPath();
    void onHttpRequestCompleted(HttpClient *sender, HttpResponse *response);
public:
    Cloud (std::string end_point) : end_point(end_point) {}
    void operator() (CloudCallback callback);
};


#endif /* Cloud_hpp */

This is the class that stores the callback passed in the constructor. Here's the implementation:

#include "Cloud.hpp"
#include <iostream>

std::string Cloud::getPath()
{
    return url + end_point;
}

void Cloud::operator()(CloudCallback callback)
{
    this->callback = callback;

    std::vector<std::string> headers;

    HttpRequest* request = new (std::nothrow) HttpRequest();
    request->setUrl(this->getPath().c_str());
    request->setRequestType(HttpRequest::Type::GET);
    request->setHeaders(headers);
    request->setResponseCallback(CC_CALLBACK_2(Cloud::onHttpRequestCompleted, this));
    HttpClient::getInstance()->send(request);
    request->release();
}

void Cloud::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response)
{
    this->callback();
}

What I'm trying to do is, make a simple Http request with the help of a functor, calling like this:

Cloud cloud("decks");
cloud([&]() {
    CCLOG("Got the decks");
});

I'm getting EXC_BAD_ACCESS(Code=EXC_I386_GPFLT) as soon as the line

this->callback();

is called.

What is it that I am doing wrong here?

Aucun commentaire:

Enregistrer un commentaire