I have 2 classes. I want to pass this
from constructor one class as a parameter to the constructor of another class.
I am aware that the error occurred because shared_from_this() is called before the IkArm object (this) is fully constructed. But I am unable to find out a way in which I an pass the node to the second class after executing the first class. Also I have gone through this question but the relationship of the classes used there is different.
The following is the code:
#include "rclcpp/rclcpp.hpp"
class IkSolver
{
public:
IkSolver(std::shared_ptr<rclcpp::Node> node) : node_(node)
{
RCLCPP_INFO(node_->get_logger(), "2nd Constructor");
}
private:
std::shared_ptr<rclcpp::Node> node_;
};
class IkArm : public rclcpp::Node
{
public:
IkArm() : Node("IkNode")
{
RCLCPP_INFO(this->get_logger(), "1st Constructor");
obj1_ = std::make_shared<IkSolver>(shared_from_this());
RCLCPP_INFO(this->get_logger(), "Back To 1st Constructor");
}
private:
std::shared_ptr<IkSolver> obj1_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<IkArm>());
rclcpp::shutdown();
return 0;
}
I am getting the following error:
[INFO] [1720452645.004303274] [IkNode]: 1st Constructor
terminate called after throwing an instance of 'std::bad_weak_ptr'
what(): bad_weak_ptr
[ros2run]: Aborted