diff --git a/rclcpp/include/rclcpp/publisher.hpp b/rclcpp/include/rclcpp/publisher.hpp index 92dbaddce5..6f3473816d 100644 --- a/rclcpp/include/rclcpp/publisher.hpp +++ b/rclcpp/include/rclcpp/publisher.hpp @@ -574,6 +574,13 @@ class Publisher : public PublisherBase std::unique_ptr duplicate_type_adapt_message_as_unique_ptr(const PublishedType & msg) { + /// Assert that the published type has no overloaded operator new since this leads to + /// new/delete mismatch (see https://github.com/ros2/rclcpp/issues/2951) + static_assert(!detail::has_overloaded_operator_new_v, + "When publishing by value (i.e. when calling publish(const T& msg)), the published " + "message type must not have an overloaded operator new. In this case, please use the " + "publish(std::unique_ptr msg) method instead."); + auto ptr = PublishedTypeAllocatorTraits::allocate(published_type_allocator_, 1); PublishedTypeAllocatorTraits::construct(published_type_allocator_, ptr, msg); return std::unique_ptr(ptr, published_type_deleter_); diff --git a/rclcpp/include/rclcpp/type_adapter.hpp b/rclcpp/include/rclcpp/type_adapter.hpp index d6834ccc22..fbbd631dce 100644 --- a/rclcpp/include/rclcpp/type_adapter.hpp +++ b/rclcpp/include/rclcpp/type_adapter.hpp @@ -16,6 +16,7 @@ #define RCLCPP__TYPE_ADAPTER_HPP_ #include +#include namespace rclcpp { @@ -128,6 +129,24 @@ struct assert_type_pair_is_specialized_type_adapter "No type adapter for this custom type/ros message type pair"); }; +template +struct has_overloaded_operator_new : std::false_type {}; +template +struct has_overloaded_operator_new>: std::true_type {}; + +template +struct has_overloaded_aligned_operator_new : std::false_type {}; +template +struct has_overloaded_aligned_operator_new> + : std::true_type {}; + +template +inline constexpr bool has_overloaded_operator_new_v = has_overloaded_operator_new::value || + has_overloaded_aligned_operator_new::value; + } // namespace detail /// Template metafunction that can make the type being adapted explicit.