ROS Resources: Documentation | Support | Discussion Forum | Service Status | Q&A answers.ros.org
Ask Your Question
0

Can I store the Subscriber object on the heap?

asked 2013-04-08 08:29:44 -0500

Gabor Juhasz gravatar image

updated 2014-01-28 17:16:05 -0500

ngrennan gravatar image

Hi,

I'd like to subscribe to topics dynamically. This is a simplified version of my current solution:

class MyClass {
    std::vector<ros::Subscriber> rosSubscriberList;
    void doSubscribe() {
        ros::Subscriber sub = n.subscribe("chatter", 1000, &whatevercallback);
        rosSubscriberList.push_back(sub);
    }
}

Which works, but I was just wondering whether if it is safe to do this.

I believe the subscriber object gets copied to the vector, then gets destructed. So for a short time there are two subscribers? Also, when the MyClass object gets destructed, does the subscriber in the list gets destructed too?

I was wondering if it would be better to have a vector of type

std::vector<ros::Subscriber*>

and handle object (subscriber) destruction manually. But then there is a copy in that solution too.

Which one would you suggest?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2013-04-08 08:38:23 -0500

dornhege gravatar image

Yes, the rosSubscriberList will also be destroyed with the class and thus all its subscribers.

Using Subscriber* in the list would solve that, but:

  • You'll get some undestroyable pointers/memory leaks
  • You could use shared_ptr here in the list, but still you'd need to copy those out to somewhere.
  • Given the list belongs to the class intuitively I'd say that this is the behaviour you'd want. If not, maybe a redesign might be better suited.
edit flag offensive delete link more

Comments

Yes, that is the behavior I want.I want to clean up everything when my class gets destroyed. Thanks for explaining.

Gabor Juhasz gravatar imageGabor Juhasz ( 2013-04-14 04:03:54 -0500 )edit

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 2013-04-08 08:29:44 -0500

Seen: 437 times

Last updated: Apr 08 '13