Can I move an object to a given address?

Suppose I have a class called "Person" Each "Person" has neighbors - represented by a collection - whose house addresses are the physical addresses within memory on the heap. If one person moves to a new address, another person immediately takes their place. How do I make such a move happen in code?

Suppose, for example, that Amy has two neighbors, Bob and Carol. Bob moves out and Dan is to move in. As a result, Amy's neighbor collection should now point to Dan when we give it a key or index related to Bob's old house.
I've played around with the memmove function today. I found that when I do something like this:
1
2
3
4
5
6
Person *bob = new Person();
bob->name = "Bob";
Person *dan = new Person();
dan->name = "Dan";
memmove(bob,dan,sizeof(Person));
cout << bob->name;


what the program does is print Dan's name instead of Bob's.
In general you should never care about the actual address of an object in memory. However, you could use the move assignment operator:
http://en.cppreference.com/w/cpp/language/move_assignment
You shouldn't need to, though.
Last edited on
memmove doesn't play nice with C++ objects.

If your name member is a std::string you have undefined behavior.

If you find yourself wanting to move an object to a particular address, there is likely a problem with your design.

For this particular case, a swap would probably be appropriate.

http://en.cppreference.com/w/cpp/algorithm/swap
cire:

I wrote the following code for a basic conversion from one user-defined class to another. However, the compiler complained that there is "no matching function for call to 'swap'".

1
2
3
4
5
6
7
8
9
10
struct AnimalConverter {
    template <typename destType> static void convert(Animal *_animal)
    {
        destType *newAnimal = new destType();
        newAnimal->name = _animal->name;
        swap(_animal, newAnimal);
        delete newAnimal;
    }
};
Last edited on
I wrote the following code for a basic conversion from one user-defined class to another.

This is a different use-case than the one presented in the OP. Swapping isn't appropriate here. That entire function looks questionable. Don't gratuitously use new.
a Person lives in a House
a House has an Address
a House has bordering Houses
a Person can move out
Topic archived. No new replies allowed.