Callback not updating class member variable

asked 2018-11-15 03:49:01 -0500

gpldecha gravatar image

I have encountered a strange problem. I have a standard class

class A{
 A(ros::NodeHandle& nh){
        sub = nh.subscribe("cmd", 10, &A::cmd_callback, this);
         cmd_received = "none";
 void cmd_callback(const std_msgs::String::ConstPtr& msg){
        cmd_received = msg->data;
        std::cout<< "cmd received in callback: " << cmd_received << std::endl;
 void update(){
   ROS_INFO_STREAM_THROTTLE(2.0, "cmd received: " << cmd_received);
   std::string cmd_received;
   ros::Subscriber sub

Now when I send a string message from my python publisher it seems to be correctly received. The print statement in the callback outputs the correct value. However when calling the update function in the main loop, the value of cmd_received is the initial one ("none").

This is seems to be a very subtle bug, normally this kind of structure works great.

Any suggestions are appreciated.

edit retag flag offensive close merge delete



We can't really debug this for you without seeing all of your code. Could you post the rest of it.

PeteBlackerThe3rd gravatar image PeteBlackerThe3rd  ( 2018-11-15 04:11:52 -0500 )edit

It is part of a larger program which I cannot put here. I detailing the symptoms to see if anyone has encountered something similar. If not, I will find a work around.

gpldecha gravatar image gpldecha  ( 2018-11-15 04:19:22 -0500 )edit

I've tried running this and it works fine on my machine running 16.04 and kinetic. Here's the test code I'm using to test. Can you run it on your machine to confirm that you still see the issue?

Gary Servin gravatar image Gary Servin  ( 2018-11-15 07:54:35 -0500 )edit

It's possible you have more than one instance of this class which is causing this bug.

PeteBlackerThe3rd gravatar image PeteBlackerThe3rd  ( 2018-11-15 09:28:36 -0500 )edit