From 4fd0e37ed9a89b1e8ea09edf6fe9e28837b701f3 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Fri, 25 Oct 2024 14:15:02 -0700 Subject: [PATCH] [wpilibc] Mechanism2d: Store roots by value --- .../native/cpp/smartdashboard/Mechanism2d.cpp | 19 +++++++------------ .../include/frc/smartdashboard/Mechanism2d.h | 2 +- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/wpilibc/src/main/native/cpp/smartdashboard/Mechanism2d.cpp b/wpilibc/src/main/native/cpp/smartdashboard/Mechanism2d.cpp index 5956071be5a..bb17180364f 100644 --- a/wpilibc/src/main/native/cpp/smartdashboard/Mechanism2d.cpp +++ b/wpilibc/src/main/native/cpp/smartdashboard/Mechanism2d.cpp @@ -22,16 +22,12 @@ Mechanism2d::Mechanism2d(double width, double height, MechanismRoot2d* Mechanism2d::GetRoot(std::string_view name, double x, double y) { - auto& obj = m_roots[name]; - if (obj) { - return obj.get(); + auto [it, isNew] = + m_roots.try_emplace(name, name, x, y, MechanismRoot2d::private_init{}); + if (isNew && m_table) { + it->second.Update(m_table->GetSubTable(name)); } - obj = std::make_unique(name, x, y, - MechanismRoot2d::private_init{}); - if (m_table) { - obj->Update(m_table->GetSubTable(name)); - } - return obj.get(); + return &it->second; } void Mechanism2d::SetBackgroundColor(const Color8Bit& color) { @@ -50,8 +46,7 @@ void Mechanism2d::InitSendable(nt::NTSendableBuilder& builder) { m_dimsPub.Set({{m_width, m_height}}); m_colorPub = m_table->GetStringTopic(kBackgroundColor).Publish(); m_colorPub.Set(m_color); - for (const auto& entry : m_roots) { - const auto& root = entry.second.get(); - root->Update(m_table->GetSubTable(entry.first)); + for (auto& entry : m_roots) { + entry.second.Update(m_table->GetSubTable(entry.first)); } } diff --git a/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h b/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h index c71bcaf75c2..f20f2deb966 100644 --- a/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h +++ b/wpilibc/src/main/native/include/frc/smartdashboard/Mechanism2d.h @@ -84,7 +84,7 @@ class Mechanism2d : public nt::NTSendable, std::string m_color; mutable wpi::mutex m_mutex; std::shared_ptr m_table; - wpi::StringMap> m_roots; + wpi::StringMap m_roots; nt::DoubleArrayPublisher m_dimsPub; nt::StringPublisher m_colorPub; };