Re: is it safe to memset a vector with zero?
=?Utf-8?B?cGFuZ28=?= <pango@discussions.microsoft.com> wrote in
news:D33CAA85-FFD7-412E-998D-B2CDE14B8498@microsoft.com:
like below code:
std::vector<int> v;
memset(&v,0,sizeof(v));
is it safe?Can I write this kind of code?
It depends a lot on what you are trying to achieve. If you are trying to
corrupt your vector so that it doesn't work, this is a great way to do it.
If, on the other hand, you are trying to initialize your vector, you have a
problem and a misconception. The problem is that the vector as declared
doesn't have any elements allocated. Therefore, there is nothing to
initialize. The misconception comes into play because when you allocate
space for a vector (via resize() or constructor argument) the elements
allocated will be initialized with whatever value you wish. By default it
will use the default constructor to create a value to initialize it with,
but you can provide your own. This means that generally you don't need to
initialize your vector with something like memset. In the case above, if I
assume you wanted a vector of 100 ints, you could write:
v.resize(100);
and you would now have 100 ints allocated each initialized to 0 (which is
the value int's default constructor uses). If I wanted it initialzed to 1,
I could write:
v.resize(100,1);
That covers one case of memset usage. The others are spelled std::fill()
or std::fill_n() in C++. I could say:
std::fill(v.begin(), v.end(), 0);
and set/reset the vector to all 0s. This works for all the containers in
the std library where assignment like this makes sense (deque, vector,
list.) The nice thing about std::fill is that is works for types other
than numerics.
std::vector<std::string> v1(100);
std::fill(v1.begin(), v1.end(), std::string("Hello World"));
Now each elements contains the string "Hello World". In this case this
could have been written:
std::vector<std::string> v1(100, "Hello World");
as well, but we were talking about std::fill() :)
Hope that helps some,
joe