• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
shaqb4

Trouble with copy constructor

10 posts in this topic

Hi, I'm reading the c++ book Beginning C++ Game Programming by Michael Dawson and one of the exercises is to make a copy constructor for a game Lobby object which has a linked list of Player objects on the heap. It's supposed to create a new memory address for all the copy's data members so that the list pointers don't point to the same instances as the original.

I created a constructor that seems to work, but I think it might more complicated than needed.

Here's the Lobby class:

[CODE]
class Lobby
{
friend ostream& operator<<(ostream& os, const Lobby& aLobby);
public:
Lobby(): m_pHead(0) {}
~Lobby() {Clear();}
Lobby(const Lobby& l);
void AddPlayer();
void RemovePlayer();
void Clear();
private:
Player* m_pHead; //First Player on list
};
[/CODE]

Here's the Player class:

[CODE]
class Player
{
public:
Player(const string& name = ""): m_Name(name), m_pNext(0) {}
string GetName() const {return m_Name;}
Player* GetNext() const {return m_pNext;}
void SetNext(Player* next) {m_pNext = next;}
private:
string m_Name;
Player* m_pNext;
};
[/CODE]

and here's the copy constructor:

[CODE]
Lobby::Lobby(const Lobby& l)
{
if (l.m_pHead != 0)
{
m_pHead = new Player;
*m_pHead = *l.m_pHead;
Player* pIter = m_pHead->GetNext();
Player* pHeap;
while (pIter != 0)
{
pHeap = new Player;
*pHeap = *pIter;
pIter = pIter->GetNext();
}
}
else
{
m_pHead = 0;
}
}
[/CODE]

Thanks, any help/explanations would be appreciated. Edited by shaqb4
0

Share this post


Link to post
Share on other sites
I haven't read the code in detail, but it's about the length I expect for copying a linked list. The last time I wrote something like that was about 15 years ago (Thank you standard C++ library!) and I seem to remember that using double pointers simplified a lot of the logic in this type of code.
0

Share this post


Link to post
Share on other sites
How else do you think it'd be possible to do something like you did that's simplier? The method you've chosen looks good to me, and is probably the best method for this job
0

Share this post


Link to post
Share on other sites
This is the type of code I remember writing with double pointers. The function `copy' is the equivalent of your copy constructor. I hope it helps:

[code]#include <iostream>

struct Node {
int data;
Node *next;
};

void copy(Node **dest, Node **orig) {
for (; *orig; orig = &(*orig)->next, dest = &(*dest)->next) {
*dest = new Node;
(*dest)->data = (*orig)->data;
}
*dest = 0;
}

void add_node(Node **list, int data) {
Node *n = new Node;
n->data = data;
n->next = *list;
*list = n;
}

void print(Node *n) {
for (; n; n = n->next)
std::cout << n->data << ' ';
std::cout << '\n';
}

void destruct(Node *n) {
Node *next;
for (; n; n = next) {
next = n->next;
delete n;
}
}

int main() {
Node *list = 0;
add_node(&list, 1);
add_node(&list, 2);
add_node(&list, 3);
print(list);
Node *another_list;
copy(&another_list, &list);
print(another_list);
destruct(list);
destruct(another_list);
}
[/code]
0

Share this post


Link to post
Share on other sites
I'm not convinced your copy constructor currently works. It appears to create copies of each of the members in the original list, but the pointer in the head node is still pointing at the original list. The copied nodes are leaked.
0

Share this post


Link to post
Share on other sites
m_pHead = new Player;
*m_pHead = *l.m_pHead;
Doesn't that create a new address for the head node? If not, how would I test it?
0

Share this post


Link to post
Share on other sites
You seem to be getting lost in your own variable names. pHeap is created, assigned and then never used for anything.

It's also weird that the code in front of your loop is exactly the same as the one inside the loop. Also, where are you setting up the next pointers? From what little code I can see, all your nodes next pointers are either pointing to the original list or to random garbage.

Your test should be to print out both lists with the players name and the address. If your code is working, all the names must be the same, but the addresses must be different.

If you don't mind a bit of headache, you can usually avoid all the "is this the head?" or "is the head NULL?" special cases by using pointer to pointer (ie. pointer to next pointer instead of using next pointer directly, so your head elements turns into just the first "next" element). But that isn't something to worry about until stuff is actually working in the first place.
1

Share this post


Link to post
Share on other sites
[quote]
Doesn't that create a new address for the head node?
[/quote]
You are allocating nodes, but you are not linking them correctly. Note that code is copying the Player instance, which implicitly copies the "next" pointer. Thus, after that line the head->next of both Lobbies point to the same sublist. Since head->next isn't subsequently modified, the loop following effectively just leaks a bunch of memory.

[quote]
If not, how would I test it?
[/quote]
Trienco's suggestion of printing both the names and addresses of the Player instances is a good one, you can visualise the list that way.
1

Share this post


Link to post
Share on other sites
Thanks, I finally got it to work with the following modified constructor. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

[CODE]
Lobby::Lobby(const Lobby& l)
{
if (l.m_pHead != 0)
{
m_pHead = new Player;
*m_pHead = *l.m_pHead;
Player* pIter = m_pHead;
Player* pHeap;
while (pIter->GetNext() != 0)
{
pHeap = new Player;
*pHeap = *pIter->GetNext();
pIter->SetNext(pHeap);
pIter = pIter->GetNext();
}
}
else
{
m_pHead = 0;
}
}
[/CODE]

Your explanations helped a lot.
0

Share this post


Link to post
Share on other sites
Consider:
[code]
Lobby::Lobby(const Lobby& other)
{
if(other.head)
{
this->head = new Player(other.head->GetName());
Player *previous = this->head;
for(Player *current = other.head->next; current ; current = current->next)
{
Player *copy = new Player(current->GetName());
previous->SetNext(copy);
previous = copy;
}
}
else
{
this->head = nullptr;
}
}
[/code]
I haven't tested this, but I believe it should work. I think it is slightly cleaner because it initialises as opposed to copies, and avoids copying pointers from the source list into the new list (even temporarily).

You could also go with the pointer to a pointer, but I find that more difficult to reason about.

Finally, neither is exception safe, these implementations will leak memory if one of the Player allocations or constructors throws an exception. But I won't go into too much detail in "For Beginners" on this point.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0