Skip to content

Commit 67276dd

Browse files
committed
Add caching mechanism for derived castPtr() in Any
Improves Any::castPtr() by caching results of std::dynamic_pointer_cast to avoid repeated casts. Adds _cached_type to track the last casted type and reuse the cached pointer. Also simplifies the case where the requested type matches the root base.
1 parent 1ce5185 commit 67276dd

File tree

1 file changed

+21
-13
lines changed

1 file changed

+21
-13
lines changed

include/behaviortree_cpp/utils/safe_any.hpp

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -368,31 +368,38 @@ class Any
368368

369369
try
370370
{
371-
// Attempt to retrieve the stored shared_ptr<Base> from the Any container
372-
auto base_ptr = linb::any_cast<std::shared_ptr<RootBase>>(&_any);
373-
if(!base_ptr)
374-
return nullptr;
375-
376371
// Case 1: If Base and Derived are the same, no casting is needed
377372
if constexpr(std::is_same_v<RootBase, Derived>)
378373
{
379-
return reinterpret_cast<T*>(base_ptr);
374+
return linb::any_cast<std::shared_ptr<RootBase>>(&_any);
380375
}
381376

382-
// Case 2: Originally stored as shared_ptr<Derived>
383-
if(_original_type == typeid(std::shared_ptr<Derived>))
377+
// Case 2: Previously cached
378+
if(_cached_type == typeid(T))
384379
{
385-
_cached_derived_ptr = std::static_pointer_cast<Derived>(*base_ptr);
386380
return reinterpret_cast<T*>(&_cached_derived_ptr);
387381
}
388382

389-
// Case 3: Fallback to dynamic cast
390-
auto derived_ptr = std::dynamic_pointer_cast<Derived>(*base_ptr);
391-
if(derived_ptr)
383+
// Attempt to retrieve the stored shared_ptr<Base> from the Any container
384+
auto base_ptr = linb::any_cast<std::shared_ptr<RootBase>>(&_any);
385+
if(!base_ptr)
386+
return nullptr;
387+
388+
// Case 3: Stored as Derived originally
389+
if(_original_type == typeid(std::shared_ptr<Derived>))
392390
{
391+
_cached_derived_ptr = std::static_pointer_cast<Derived>(*base_ptr);
392+
}
393+
// Case 4: Fallback to dynamic cast
394+
else
395+
{
396+
auto derived_ptr = std::dynamic_pointer_cast<Derived>(*base_ptr);
397+
if(!derived_ptr)
398+
return nullptr;
393399
_cached_derived_ptr = derived_ptr;
394-
return reinterpret_cast<T*>(&_cached_derived_ptr);
395400
}
401+
_cached_type = typeid(T);
402+
return reinterpret_cast<T*>(&_cached_derived_ptr);
396403
}
397404
catch(...)
398405
{
@@ -427,6 +434,7 @@ class Any
427434
linb::any _any;
428435
std::type_index _original_type;
429436
mutable std::shared_ptr<void> _cached_derived_ptr = nullptr;
437+
mutable std::type_index _cached_type = typeid(void);
430438

431439
//----------------------------
432440

0 commit comments

Comments
 (0)