Re: std::vector and a bit-wise copy
On Feb 9, 3:24 pm, Jeremy <bjerem...@yahoo.com> wrote:
I have a question that I having trouble finding a straight answer to,
but thought it may be obvious to someone here.
If I have a struct with a vector as a member:
struct A
{
std::vector<int> theVec;
};
And I make two instances of that vector x and y and populate the
vector in x. Is it undefined behavior to then set y= x ? Such as
int main()
{
A x;
A y;
fill(x); // allocates the vector and populates it
y = x;
}
Seeing A has no copy-constructor declared, we should do a bit-wise
copy from x to y. Since the vector in y has no memory allocated to it,
I'm assuming this should be just a case of memory trampling and
exhibit UB.
Is that wrong or am I missing something w.r.t. the bit-wise copy?
If there is no explicitly defined copy constructor or assignment
operator in a class (or struct) type, then the compiler will attempt
to provide a default one. The default is member-wise copy construction
or assignment.
In this case, you are using the compiler provided default assignment
operator "A& A::operator= (A Const& )". The default is member-wise
assignment of the members according to their "operator=". In this
case, the compiler default "A& A::operator= (A Const& )" will be as
if:
A& A::operator= (A Const& rhs)
{
theVec = rhs.theVec;
return *this;
}
The assignment of the std::vector member is definitely not a simple
bitwise copy of its internal members, and thus there is no simple
bitwise copy in that program fragment.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]