• 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
ptchaos

Error accessing vector member

9 posts in this topic

Greetings,
been a long time in manage world and now I'm going back to C++.

Trying to do a small object management, but I'm having an error that I can't figure out.

Reduced the project to a smallest possible to show my issue:
(the identation got a bit messed up on copy/paste)

[code]
#include <iostream>
#include <vector>
using namespace std;
//
class cControl
{
public:
virtual void Draw()
{
cout << "Control" << endl;
};
};
//
class cLabel: public cControl
{
public:
cLabel()
{
}
//
void Draw()
{
cout << "Label" << endl;
}
};
//
class cControls
{
public:
vector<cControl*> listControls;

//
cLabel CreateLabel()
{
cLabel label;
// #1
//this->AddControl(&label);
return(label);
}

//
void AddControl(cControl *control)
{
this->listControls.push_back(control);
}
//
void Draw()
{
for(cControl *ctrl: listControls)
ctrl->Draw();
}
};
//
int main()
{
cControls controls;

cLabel label1=controls.CreateLabel();
// #2
controls.AddControl(&label1);
//
controls.Draw();
//
cin.get();
//
return(EXIT_SUCCESS);
}

[/code]

The point is to have a base control class that others will derive (label, textbox, line, panel, etc).
I've pointed the problem with #1 and #2.
If I add the control to the list in the main function (#2), it works fine and it calls Draw from label correctly.
But if I comment #2 and uncomment #1, so it adds automatically to list when creating label, it crashes when trying to call Draw from label.

From what I've checked, when the label is added to the vector inside the CreateLabel function, something changes when it gets out of that function, which makes unaccessible when calling the Draw.

Can anyone point me out to the correct path?

Thanks,
chaos
0

Share this post


Link to post
Share on other sites
[quote name='SiCrane' timestamp='1352047907' post='4997216']
Your cLabel objects are created on the stack and you are storing pointers to them in the vectors. This is bad juju as they get destroyed when the function that contains them exits. Two possible fixes are either heap allocate them with new or store by value rather than by pointer.
[/quote]
Awesome SiCrane, thank you so much.

I've changed to:
[code]
cLabel *CreateLabel()
{
cLabel *pLabel=new cLabel();
// #1
this->AddControl(pLabel);
return(pLabel);
}
[/code]

Seems to be working fine now


Thanks,
chaos
0

Share this post


Link to post
Share on other sites
[quote name='Trienco' timestamp='1352092874' post='4997443']
Of course now you have to ask yourself who is responsible for cleaning it up and when should that happen. Rule of thumb: for every "new" that isn't assigned to a smart pointer, there must be one (and only one) "delete".[/quote]
I'm deleting in the destructor of controls class. Don't know if its enough. Something like this:
[code]~cControls()
{
for(cControl *ctrl : this->listControls)
delete ctrl;
}[/code]


[quote name='Servant of the Lord' timestamp='1352095112' post='4997451']
So, either you need to A) manually micro-manage your memory, or B) Let C++ manage your memory for you using smart pointers.
[/quote]
Yeah I know. I still have in my checkup list the use of smart pointers, since I've seen that's whats being used to ease memory management.



[quote name='Servant of the Lord' timestamp='1352095112' post='4997451']Why's every one of your classes start with the lowercase letter 'c', and what does it stand for? If 'c' stands for 'class', that's a little bit redundant don't you think? [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
([size=2]See:[/size] [size=2][[url="http://www.jelovic.com/articles/stupid_naming.htm"]CStupidClassName[/url]] [/size][size=2]Sometimes programmers see someone else do something, don't know why it's there, adopt the practice, and then spread that practice to other programmers[/size])
[/quote]
LOL, I've been using that for a while, didn't knew it was a thing.
I usually use the c as a prefix for instanced classes and without the c for static (singleton).


Thanks for the comments guys,
chaos
0

Share this post


Link to post
Share on other sites
[quote name='ptchaos' timestamp='1352104442' post='4997494']
I'm deleting in the destructor of controls class. Don't know if its enough. Something like this:
[code]~cControls()
{
for(cControl *ctrl : this->listControls)
delete ctrl;
}[/code]
[/quote]
That's correct.

You might want to return cControl as a pointer from your 'Create' functions as well.

[code]//Creates a label and returns a pointer to it. cControls retains ownership, and the label will be destroyed in cControls' destructor.
cLabel *cControls::CreateLabel()
{
cLabel *newLabel = new cLabel(); //Should be replaced with smart pointers in the future.

this->AddControl(newLabel);

return newLabel;
}[/code]
(Because code blocks are currently messing up, I posted the code [url="http://codepad.org/PxyMUmq8"]here[/url])

However, what if you want to pass parameters to the cLabel's constructor? Since you *are* using C++11 (your for-range loop), you can use C++11's perfect forwarding like this:
[code]//Creates a label and returns a pointer to it. cControls retains ownership, and the label will be destroyed in cControls' destructor.
template<typename Arg>
cLabel *cControls::CreateLabel(Arg &&arg)
{
cLabel *newLabel = new cLabel(std::forward<Arg>(arg));
this->AddControl(newLabel);

return newLabel;
}[/code]
[url="http://codepad.org/1BGGUH3A"]Code here[/url]

And you can then pass the cLabel constructor arguments (any number of them) directly to CreateLabel:
[code]myControls.CreateLabel("My text", Color(255,0,0), Style::Bold);[/code]
That would internally call 'cLabel("My text", Color(255,0,0), Style::Bold)' without cLabel having to change anything about it.

But, you could even go a step further, and make your CreateLabel() work for [i]any [/i]class that derives from cControl.
[code]//Creates a cControl and returns a pointer to it. cControls retains ownership, and the label will be destroyed in cControls' destructor.
template<typename ControlType, typename Arg>
ControlType *cControls::Create(Arg &&arg)
{
ControlType *newControl = new ControlType(std::forward<Arg>(arg));
this->AddControl(newControl);

return newControl;
}[/code]
[url="http://codepad.org/Bsj0Udpx"]Code here[/url]

And you can use it like this:
[code]myControls.Create<cLabel>("My text", Color(255,0,0), Style::Bold);
myControls.Create<cLineEdit>("Default text", Characters::Letters | Characters::Numbers | Characters::Symbols);
cMenu *menu = myControls.Create<cMenu>({"First item", "Second item", "Third item"});
menu->DoSomething();
[/code]
[url="http://codepad.org/pv385lih"]Code here[/url]
...and not need to write a new CreateX() function for each type of control you make. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

Those functions would've shared 90% of the same code anyway, and the 10% that is different can be handled by templates. Plus, if you ever wrap your code in a DLL, and later decide to create new cControl-derived classes specific to a certain project, you'd have to add new functions to cControls and recompile the DLL needlessly (with project-specific additions). But with this way, it's completely avoided. [img]http://public.gamedev.net//public/style_emoticons/default/wink.png[/img] Edited by Servant of the Lord
1

Share this post


Link to post
Share on other sites
/bow
Thanks for taking time to give suggestions, you guys are awesome.

That forward "thing" looks interesting. I need to invest more time in the new features.

~10 years in manage code and coming back feels a totally new language [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]


Thanks again [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
chaos
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