L
Larry Brasfield
Ioannis Vranos said:Ioannis Vranos wrote:
[Cut many words about validity of byte-wise copying.]
As I mentioned, copying byte by byte is ok in my book.
4. The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T,
where N equals sizeof(T). The value representation of an object is the set of bits
that hold the value of type T. For POD types, the value representation is a set of bits in the object representation that
determines a value, which is one discrete element of an implementation-defined set of values.37)
5. Object types have alignment requirements (3.9.1, 3.9.2). The alignment of a complete object type is an implementation-defined
integer value representing a number of bytes; an object is allocated at an address that meets the alignment requirements of its
object type."
Unfortunately you are right.
Well, I suppose one could look at it that way. However, the
alignment issue arises from machine design decisions that are
made in the interest of cost, complexity and speed. So, to
the extent that having alignment requirements has made some
computers cheaper, more reliable and faster, they might be
regarded as fortunate by the beneficiaries.
Case 3:
At first the destination must be a pointer of the same object type (and presumably the allocated space must be for the same type
objects.
Secondly, the standard guarantees that only memcpy() works in this case, and not copying it char by char or unsigned char by
unsigned char. In other words, in an implementation memcpy() can be defined in some exotic way (e.g. assembly), and still copying
it unsigned char by unsigned char to the destination has undefined behaviour, while using memcpy() for the same destination is
guaranteed to work!
I think file I/O is supposed to work, too. And the language
about value residing in the bytes seems, to me, to guarantee
that any sizeof(T) byte-by-byte copy would preserve value.
So my examples fixed (and not producing exactly the same results):
Please see inserted comments.
#include <iostream>
#include <cstring>
int main()
{
using namespace std;
int integer=4;
int secondInteger;
memcpy(&secondInteger, &integer, sizeof(integer));
cout<<integer<<"\n";
}
Must emit '4' and a line boundary and is portable.
and
#include <iostream>
#include <cstring>
int main()
{
using namespace std;
int arrayInt[4]={1,2,3,4};
int secondArrayInt[sizeof(arrayInt)];
Do you mean to create these 2 arrays the same size?
That is not the effect of the above code.
memcpy(secondArrayInt, arrayInt, sizeof(arrayInt));
for(unsigned i=0; i< sizeof(4); ++i)
cout<<secondArrayInt<<"\n";
}
The sizeof(4) is the same as sizeof(int).
Please correct if I am wrong. Aren't the above guaranteed to be portable?
It will emit a number of integers in text format which
varies according to how many bytes an int occupies.
Not portable by my definition of the term.