Publish message on destructor works only on rclpy
Hi everyone,
In a test node I just have one publisher that publishes the node state once on the constructor and once on the destructor of my node class. I figured out that this works on Python3 (rclpy) and not on C++ (rclcpp).
import rclpy
from rclpy.node import Node
import time
from std_msgs.msg import String
class Test(Node):
def __init__(self):
super().__init__('test')
self.publisher = self.create_publisher(String, 'state_test', 10)
msg = String()
msg.data = "Node started"
self.publisher.publish(msg)
def __del__(self):
msg = String()
msg.data = "Node crashed"
self.publisher.publish(msg)
def main(args=None):
rclpy.init(args=args)
node_test = Test()
rclpy.spin(node_test)
node_test.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
C++ code:
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
class Test : public rclcpp::Node
{
public:
Test()
: Node("test"), count_(0)
{
pub_state = this->create_publisher<std_msgs::msg::String>("state_test", 10);
auto message = std_msgs::msg::String();
message.data = "Node started";
pub_state->publish(message);
}
~Test()
{
auto message = std_msgs::msg::String();
message.data = "Node crashed";
pub_state->publish(message);
}
private:
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr pub_state;
size_t count_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<Test>());
rclcpp::shutdown();
return 0;
}
Why is the result different on those two examples ?
Isn't that obvious? In python you are explicitly calling the destruction before calling shutdown. In C++ you don't do that, so the destructor will only be called when the variable goes out of scope, i.e., after the shutdown when it can't publish anymore.