Reputation: 4732
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;
};
Upvotes: 1
Views: 128
Reputation: 27133
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 move
d 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.
Upvotes: 1