Avoid extra copy in Vector/CowData push_back/insert

Update push_back/insert methods to move new item into CowData instead of copying
This commit is contained in:
aaronp64
2025-11-10 10:27:55 -05:00
parent 2d86b69bf1
commit afd59b36cf
2 changed files with 9 additions and 9 deletions

View File

@ -206,8 +206,8 @@ public:
_FORCE_INLINE_ void remove_at(Size p_index);
Error insert(Size p_pos, const T &p_val);
Error push_back(const T &p_val);
Error insert(Size p_pos, T &&p_val);
Error push_back(T &&p_val);
_FORCE_INLINE_ operator Span<T>() const { return Span<T>(ptr(), size()); }
_FORCE_INLINE_ Span<T> span() const { return operator Span<T>(); }
@ -296,7 +296,7 @@ void CowData<T>::remove_at(Size p_index) {
}
template <typename T>
Error CowData<T>::insert(Size p_pos, const T &p_val) {
Error CowData<T>::insert(Size p_pos, T &&p_val) {
const Size new_size = size() + 1;
ERR_FAIL_INDEX_V(p_pos, new_size, ERR_INVALID_PARAMETER);
@ -326,13 +326,13 @@ Error CowData<T>::insert(Size p_pos, const T &p_val) {
}
// Create the new element at the given index.
memnew_placement(_ptr + p_pos, T(p_val));
memnew_placement(_ptr + p_pos, T(std::move(p_val)));
return OK;
}
template <typename T>
Error CowData<T>::push_back(const T &p_val) {
Error CowData<T>::push_back(T &&p_val) {
const Size new_size = size() + 1;
if (!_ptr) {
@ -361,7 +361,7 @@ Error CowData<T>::push_back(const T &p_val) {
}
// Create the new element at the given index.
memnew_placement(_ptr + new_size - 1, T(p_val));
memnew_placement(_ptr + new_size - 1, T(std::move(p_val)));
return OK;
}

View File

@ -71,8 +71,8 @@ private:
public:
// Must take a copy instead of a reference (see GH-31736).
_FORCE_INLINE_ bool push_back(T p_elem) { return _cowdata.push_back(p_elem); }
_FORCE_INLINE_ bool append(const T &p_elem) { return push_back(p_elem); } //alias
_FORCE_INLINE_ bool push_back(T p_elem) { return _cowdata.push_back(std::move(p_elem)); }
_FORCE_INLINE_ bool append(T p_elem) { return _cowdata.push_back(std::move(p_elem)); } //alias
void fill(T p_elem);
void remove_at(Size p_index) { _cowdata.remove_at(p_index); }
@ -133,7 +133,7 @@ public:
_FORCE_INLINE_ const T &operator[](Size p_index) const { return _cowdata.get(p_index); }
// Must take a copy instead of a reference (see GH-31736).
Error insert(Size p_pos, T p_val) { return _cowdata.insert(p_pos, p_val); }
Error insert(Size p_pos, T p_val) { return _cowdata.insert(p_pos, std::move(p_val)); }
Size find(const T &p_val, Size p_from = 0) const {
if (p_from < 0) {
p_from = size() + p_from;