我正在尝试在我自己的仿函数中包装一个HttpRequest对象(来自Cocos2d-x)。除了调用传递给我的仿函数的回调之外,一切正常。你能发现下面的课程中的错误吗? (我只粘贴了代码的相关部分)。
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 */
这是存储构造函数中传递的回调的类。这是实施:
#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();
}
我要做的是,在一个仿函数的帮助下做一个简单的Http请求,这样调用:
Cloud cloud("decks");
cloud([&]() {
CCLOG("Got the decks");
});
我一旦获得EXC_BAD_ACCESS(代码= EXC_I386_GPFLT)
this->callback();
被召唤。
我在这里做错了什么?
编辑:现在我猜这与线程有关。如果我删除HttpRequest并立即调用传递给operator()的回调方法,这没有任何问题。乞求帮助: - )
答案 0 :(得分:0)
试试这个:
void Cloud::operator()(const CloudCallback &callback)