From 6eb135855f9f758766f72e011445150543011361 Mon Sep 17 00:00:00 2001 From: "C. Weaver" Date: Fri, 16 Apr 2021 23:24:49 -0400 Subject: [PATCH] Eliminate unnecessary allocations when copying default constructed SU_vectors --- src/SUNalg.cpp | 8 +++++--- test/copy_construct_SU_vector.test.cpp | 12 ++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/SUNalg.cpp b/src/SUNalg.cpp index 0ffb9fc..c94012f 100755 --- a/src/SUNalg.cpp +++ b/src/SUNalg.cpp @@ -86,10 +86,12 @@ isinit_d(false){} SU_vector::SU_vector(const SU_vector& V): dim(V.dim), size(V.size), -isinit(true), +isinit(V.isinit || V.isinit_d), isinit_d(false){ - alloc_aligned(dim,size,components,ptr_offset); - std::copy(V.components,V.components+size,components); + if(isinit){ + alloc_aligned(dim,size,components,ptr_offset); + std::copy(V.components,V.components+size,components); + } } SU_vector::SU_vector(SU_vector&& V): diff --git a/test/copy_construct_SU_vector.test.cpp b/test/copy_construct_SU_vector.test.cpp index be94dfb..b9a4639 100755 --- a/test/copy_construct_SU_vector.test.cpp +++ b/test/copy_construct_SU_vector.test.cpp @@ -54,9 +54,21 @@ void exercise_constructor(unsigned int dim){ std::cout << '\n'; } +void copy_empty(){ + SU_vector v1; //owns and refers to no memory + CLEAR_MEM_CACHE; + alloc_counting::reset_allocation_counters(); + SU_vector v2(v1); //should not allocate + auto allocated=alloc_counting::mem_allocated; + if(allocated) + std::cout << allocated << " bytes allocated when no allocation should occur\n"; +} + int main(){ alloc_counting::pattern_fill_allocs=true; alloc_counting::alloc_fill_pattern=0xFF; for(unsigned int i=2; i<=6; i++) exercise_constructor(i); + + copy_empty(); }