http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58483
Bug ID: 58483 Summary: missing optimization opportunity for const std::vector compared to std::array Product: gcc Version: 4.8.1 Status: UNCONFIRMED Severity: enhancement Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: dl.soluz at gmx dot net this small testprogram shows a missing optimization opportunity for const std::vector when using initialization_list - in compared to std::array #include <vector> #include <numeric> #include <array> static int calc(const std::array<int,3> p_ints, const int& p_init) //static int calc(const std::vector<int> p_ints, const int& p_init) { return std::accumulate(p_ints.begin(), p_ints.end(), p_init); } int main() { const int result = calc({10,20,30},100); return result; } optimizer-result using std::array int main() () { <bb 2>: return 160; } the result using std::vector int main() () { int __init; int _2; int _11; int _32; int * _33; <bb 2>: _33 = operator new (12); __builtin_memcpy (_33, &._79, 12); _32 = MEM[(const int &)_33]; __init_28 = _32 + 100; _2 = MEM[(const int &)_33 + 4]; __init_18 = _2 + __init_28; _11 = MEM[(const int &)_33 + 8]; __init_13 = _11 + __init_18; if (_33 != 0B) goto <bb 3>; else goto <bb 4>; <bb 3>: operator delete (_33); <bb 4>: return __init_13; } according to Marc Gliss's answer in (http://gcc.gnu.org/ml/gcc/2013-09/msg00179.html) "... We don't perform such high-level optimizations. But if you expand, inline and simplify this program, the optimizers sees something like: p=operator new(12); memcpy(p,M,12); // M contains {10, 20, 30} res=100+p[0]+p[1]+p[2]; if(p!=0) operator delete(p); A few things that go wrong: * because p is filled with memcpy and not with regular assignments, the compiler doesn't realize that p[0] is known. * the test p != 0 is unnecessary (a patch that should help is pending review) * we would then be left with: p=new(12); delete p; return 160; gcc knows how to remove free(malloc(12)) but not the C++ variant (I don't even know if it is legal, or what conditions and flags are required to make it so). ..." the pending patch is http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19476 but the question is still can new(delete(12)) also removed like free(malloc(12)) in this scenario?