subscriber callback unable to access class member
I'm not really sure if this is a ROS problem or a C++ problem, but it's blowing my mind.
- I have a class with a vector of structs in it.
- I construct some structs and
push_back
them into the vector - In the constructor of the struct, I create a subscriber
- The callback of this subscriber is a member function of the struct.
- The subscriber successfully gets called when a message is published, but the callback doesn't have valid member data.
My question is: what is going on here? I know a few quick ways to solve the problem, but they're kind of cheating, and anyway, I want to understand. I'm thinking it's either that I'm unaware of some threading issue ros is doing behind the scenes, or the this
pointer isn't getting correctly to the subscriber. But I've tried everything I could think to do.
Here's a minimal example like what I'm trying to do:
#include <ros/ros.h>
#include <std_msgs/Bool.h>
struct S{
ros::NodeHandle n;
ros::Subscriber subscriber;
unsigned int _number;
S(std::string topic_name, unsigned int number){
_number = number;
ROS_INFO("the number is %i",_number); //prints out as 5
subscriber = n.subscribe<std_msgs::Bool>(topic_name, 1, &S::S_cb, this);
}
void S_cb(const std_msgs::Bool::ConstPtr &msg){
ROS_INFO("performing foo on %i", _number); //prints out as 0 - why???
//foo(_number, msg->data);
}
};
class TestNode{
ros::NodeHandle n;
std::vector<S> s_array;
public:
TestNode(std::string name){
s_array.push_back(S("test_topic",5));
}
~TestNode(){ }
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "test_node");
TestNode tn(ros::this_node::getName());
ros::spin();
return 0;
}
Does this compile? Shouldn't S need a S() constructor to be put into a vector?
I didn't compile the above test case (probably should have...), but the real code it's based on compiles fine. Anyway, according to [cplusplus.com](http://www.cplusplus.com/reference/vector/vector/vector/), this way to initialize a vector creates a vector of 0 S elements, so no Ss are constructed until push_back happens
Doesn't matter. You can still call resize(n) that will default construct n elements. My guess is this should give a compile error.