1

What is the best way to initialize a vector member object in C++11? Will the compiler optimize away the copy in foo or will bar be more efficient?

#include <vector> using namespace std; // C++11 style struct foo { vector<int> vec = vector<int>(256); }; // traditional struct bar { bar() : vec(256) {} vector<int> vec; }; 
5
  • 2
    usually it's best to start a vector as empty since push_back is actually very efficient Commented Nov 7, 2013 at 0:16
  • @aaronman, good point. And if you're determined to give some hint to the system about the expected size, there's alway vector::reserve Commented Nov 7, 2013 at 0:23
  • 1
    Default-initialized dynamic arrays are weird in C++. C++ separates memory allocation from object creation, so you should maybe allocate the memory up front (with reserve), but only create the objects when you actually have them. (For example, default-initialization of a vector causes all the elements to be accessed, which may be unnecessary and wasteful.) Commented Nov 7, 2013 at 0:26
  • @KerrekSB that's why they were supposed to add std::dynarray but it was taken out Commented Nov 7, 2013 at 0:31
  • @aaronman: Mm, I think even that would have initialized the elements. I'm not sure, though. Commented Nov 7, 2013 at 0:33

1 Answer 1

1

In C++11 there probably isn't much difference between them. For example foo does not copy a large vector. The right hand side of the = is an rvalue and will be moved to the left hand side. The only difference is the creation (and quick removal) of the 0-element vector within foo. But that'll take up no time.

But, both C++11 and C++03 allow optimizations ('elision') to skip the assignment in foo. Therefore they can both be very efficient in both standards.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.