From d09aa8ade534b78f8b947b91068a53dea0dd2d55 Mon Sep 17 00:00:00 2001 From: Matthias Grob Date: Wed, 20 Dec 2023 11:58:13 +0100 Subject: [PATCH] matrix: fix slice to slice assignment to do deep copy To fix usage of a.xy() = b.xy() which should copy the first two elements over into a and not act on a copy of a. --- src/lib/matrix/matrix/Slice.hpp | 8 ++++++++ src/lib/matrix/test/MatrixSliceTest.cpp | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/src/lib/matrix/matrix/Slice.hpp b/src/lib/matrix/matrix/Slice.hpp index 207d21fdd9..da995a420b 100644 --- a/src/lib/matrix/matrix/Slice.hpp +++ b/src/lib/matrix/matrix/Slice.hpp @@ -35,6 +35,8 @@ public: assert(y0 + Q <= N); } + Slice(const Slice &other) = default; + const Type &operator()(size_t i, size_t j) const { assert(i < P); @@ -52,6 +54,12 @@ public: return (*_data)(_x0 + i, _y0 + j); } + // Separate function needed otherwise the default copy constructor matches before the deep copy implementation + Slice &operator=(const Slice &other) + { + return this->operator=(other); + } + template Slice &operator=(const Slice &other) { diff --git a/src/lib/matrix/test/MatrixSliceTest.cpp b/src/lib/matrix/test/MatrixSliceTest.cpp index 7849259c65..9240e6b5a8 100644 --- a/src/lib/matrix/test/MatrixSliceTest.cpp +++ b/src/lib/matrix/test/MatrixSliceTest.cpp @@ -262,3 +262,12 @@ TEST(MatrixSliceTest, Slice) float O_check_data_12 [4] = {2.5, 3, 4, 5}; EXPECT_EQ(res_12, (SquareMatrix(O_check_data_12))); } + +TEST(MatrixSliceTest, XYAssignmentTest) +{ + Vector3f a(1, 2, 3); + Vector3f b(4, 5, 6); + // Assign first two elements from b to first two slot of a + a.xy() = b.xy(); + EXPECT_EQ(a, Vector3f(4, 5, 3)); +}