From 5172ab8fd0448e6eb5fbbcd5128399c64d7f9edb Mon Sep 17 00:00:00 2001 From: Starlight220 <53231611+Starlight220@users.noreply.github.com> Date: Sun, 3 Dec 2023 02:45:04 +0200 Subject: [PATCH] [commands] C++ CommandPtr: Prevent null initialization (#5991) --- .../src/main/native/cpp/frc2/command/CommandPtr.cpp | 5 +++++ .../src/main/native/include/frc2/command/CommandPtr.h | 5 +++-- .../src/test/native/cpp/frc2/command/CommandPtrTest.cpp | 4 ++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandPtr.cpp b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandPtr.cpp index 6f7e41837a..cbbcc14640 100644 --- a/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandPtr.cpp +++ b/wpilibNewCommands/src/main/native/cpp/frc2/command/CommandPtr.cpp @@ -22,6 +22,11 @@ using namespace frc2; +CommandPtr::CommandPtr(std::unique_ptr&& command) + : m_ptr(std::move(command)) { + AssertValid(); +} + void CommandPtr::AssertValid() const { if (!m_ptr) { throw FRC_MakeError(frc::err::CommandIllegalUse, diff --git a/wpilibNewCommands/src/main/native/include/frc2/command/CommandPtr.h b/wpilibNewCommands/src/main/native/include/frc2/command/CommandPtr.h index ae8c11819f..ed11d5defc 100644 --- a/wpilibNewCommands/src/main/native/include/frc2/command/CommandPtr.h +++ b/wpilibNewCommands/src/main/native/include/frc2/command/CommandPtr.h @@ -27,8 +27,7 @@ namespace frc2 { */ class CommandPtr final { public: - explicit CommandPtr(std::unique_ptr&& command) - : m_ptr(std::move(command)) {} + explicit CommandPtr(std::unique_ptr&& command); template T> // NOLINTNEXTLINE(bugprone-forwarding-reference-overload) @@ -39,6 +38,8 @@ class CommandPtr final { CommandPtr(CommandPtr&&) = default; CommandPtr& operator=(CommandPtr&&) = default; + explicit CommandPtr(std::nullptr_t) = delete; + /** * Decorates this command to run repeatedly, restarting it when it ends, until * this command is interrupted. The decorated command can still be canceled. diff --git a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandPtrTest.cpp b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandPtrTest.cpp index 6c57c7f9fa..75ec040964 100644 --- a/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandPtrTest.cpp +++ b/wpilibNewCommands/src/test/native/cpp/frc2/command/CommandPtrTest.cpp @@ -34,3 +34,7 @@ TEST_F(CommandPtrTest, MovedFrom) { EXPECT_EQ(1, counter); } + +TEST_F(CommandPtrTest, NullInitialization) { + EXPECT_THROW(CommandPtr{std::unique_ptr{}}, frc::RuntimeError); +}