Ask Your Question

Subscriber callback in class defined as shared_ptr

asked 2017-05-19 08:49:04 -0600

l4ncelot gravatar image


I have very weird problem. I'm trying to set callback function to one of my subscribers. The problem is that the object, in which the callback function is declared, is defined as std::shared_ptr. Let me give you an example. Assume we have 2 classes, class A and B.

Class A looks like this:

#include <ros/ros.h>

class A {
    A(const ros::NodeHandle& nh) : nh_(nh), subscriber_(nh_.subscribe("topic", 10, &B::callback, b_.get())){
        b_ = std::make_shared<B>(nh_);    

    ros::NodeHandle nh_;
    ros::Subscriber subscriber_;    

    std::shared_ptr<B> b_;

And class B looks like this:

#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>

class B {
    B(const ros::NodeHandle& nh) : nh_(nh) {}

    callback(const geometry_msgs::PoseStampedConstPtr& pose){
        value_ = 1.0;
   double value_{0.0};

And this obviously doesn't work for some reason. The strange thing is that I can only ROS_INFO the data coming to my topic in callback function, but not modify any member variables in class B. I think it has to do something with callback function looking at "wrong place". Normally I can modify member variables without problem.

Is there some solution to this? Is it even possible to point callback to function in class defined as std::shared_ptr?

Thank you for any advice.

edit retag flag offensive close merge delete


Please post your compiler warnings/error or an example log. Do you have a spinner somewhere? See

VictorLamoine gravatar image VictorLamoine  ( 2017-05-19 10:53:55 -0600 )edit

Well I do have a spinner there, it would be impossible to ROS_INFO the callback function without it. There's no problem with compilation. It just crashes during runtime.

l4ncelot gravatar image l4ncelot  ( 2017-05-23 03:51:13 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2017-05-23 11:14:56 -0600

l4ncelot gravatar image

I figured out the problem already. The problem was that firsly I initialized object B as nullptr which led to runtime error. After creating some pointer instead of nullptr, I was able to modify the member variables.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools



Asked: 2017-05-19 08:49:04 -0600

Seen: 711 times

Last updated: May 23 '17