Re: Okay to move an object?
Frederick Gotham wrote:
Are you saying that it is indeed acceptable for an object to store its
own address within itself (or the address of a member object, or base
class object)? If so, I'll have to take this into account when moving the
object's bytes to another location in memory.
Of course it's acceptable. Not only that, but it's common practice.
You can't take that into account in general, because objects are
opaque. Each object has a different set of rules for copying that
object. For some objects, the rule is simply that the object is not
copyable.
Objects are encapsulated in C++. If there isn't a copy constructor
provided, then you'd have to go behind the scenes, and break the
encapsulation.
The general case of this problem is intractable.
But there is also another problem: memory copying objects is a waste of
computing time. In general, programming is done by leaving objects
where they are and moving around only references to these objects. This
is so entrenched in computing that some programming languages only have
reference variables for objects that do not fit into a word of memory.
Those objects are never moved (except, perhaps, by garbage collection).
In C++ reference variables are emulated using pointers. (There are also
specially attributed values called references, but these are not
variables).
If you have a set of objects and you want to put them into an array and
shuffle that array, you should make it an array of pointers to these
objects. You move the pointers, and that pointer array then gives you a
rearranged /view/ on these objects, which actually stayed exactly where
they were.
Moreover, those objects don't have to be allocated in a contiguous
region of memory, either!
When the "RotateArrayOnce" function is invoked, I can assume that nothing
will be depending upon its original address. (It's the programmer's
responsibility to ensure this before invoking my reusable code).
But when programmers learn about that responsibility, they might not be
reusing that code.
After all, the programmer would not re-arrange an array if the addresses
of the array's elements were of significance.
Ah but the programmer /could/ if the array only held pointers to the
objects.