Compiler optimizations of copying PODs

T

tommy.hinks

I am wondering if anyone knows how compilers auto-generate copy
constructors for PODs. Let me explain what I mean with an example:

struct A
{
int u;
int v;
};

If I were to write the copy constructor for the POD myself, I would
write it like this:

A::A(const A rhs)
: u(rhs.u), v(rhs.v) {}

the main point being that the member variables are initialized upon
creation, and not created and then assigned a value, like this:

A::A(const A rhs)
{
u = rhs.u;
v = rhs.v;
}

Or perhaps some other form of bitwise (shallow) copying is done by the
compiler for auto-generated PODs?

Any thoughs on this?

Thanks,

T
 
K

Kai-Uwe Bux

I am wondering if anyone knows how compilers auto-generate copy
constructors for PODs. Let me explain what I mean with an example:

struct A
{
int u;
int v;
};

If I were to write the copy constructor for the POD myself, I would
write it like this:

A::A(const A rhs)
: u(rhs.u), v(rhs.v) {}
[snip]

This is exactly what the compiler generated copy-constructor will do:
member-wise copying. [BTW: this is also what the complier generates for
non-PODs.]


Best

Kai-Uwe Bux
 
A

Andrey Tarasevich

Kai-Uwe Bux said:
struct A
{
int u;
int v;
};

If I were to write the copy constructor for the POD myself, I would
write it like this:

A::A(const A rhs)
: u(rhs.u), v(rhs.v) {}
[snip]

This is exactly what the compiler generated copy-constructor will do:
member-wise copying. [BTW: this is also what the complier generates for
non-PODs.]

Except that it should take its argument by reference

A::A(const A& rhs) : u(rhs.u), v(rhs.v) {}

And, of course, that's how it will look conceptually. The question the OP is
asking ("initialized upon creation" or "created and then assigned a value")
doesn't really make much sense if we step down to the level of what compiler
does internally. It can do anything as long as the result is correct. Most of
the time for POD the compiler will generate something like

inline A::A(const A& rhs) { memcpy(this, &rhs, sizeof(A)); }
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top