• 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.
  • entries
    46
  • comments
    91
  • views
    64107

Fun with Modern C++ and Smart Pointers

Sign in to follow this  
Followers 0
Squared'D

7297 views

This has been re-posted to http://articles.squaredprogramming.com/2014/02/smartpointers.html

_________________

This is a journal entry not an article so I feel like I can ramble a bit before I get to the main point. I have been programming for some time now and got my CS degree way back in 2003, but in 2007, I decided to take a break from programming, moved to South Korea, and have been an English teach ever since. I started to program again and with the help of an artist friend of mine, made this for last year's IGF. We obviously didn't win and haven't decided whether or not to continue with the project.

Anyway, because of my long hiatus from programming, quite a few things have passed me by, namely modern C++ and all of this smart pointer stuff. I've decided to start writing code not just for myself, but code that others could use so I want to update my knowledge of C++ and explore smart pointers. In this journal entry I want to share what I've learned. I don't claim to be an expert, so if you have any useful insights or corrections, I'd appreciate a "friendly" comment.


Raw Pointer Primer


There are two basic ways to create a variable in C++: stack variables and heap allocations. Stack variables are defined inside a certain scope and as long as you're in that scope, the variable will exist. Heap allocations (dynamically allocated memory), variables typically declared with new or malloc, aren't not defined within a scope and will exist until the memory is freed.

Here's an example:void foo(){ // Object A of class CSomeClass has been declared inside the scope of foo CSomeClass A; // do some stuff .... // you can even call other functions and use A as a parameter Func1(A); // This could be pass by value or pass by reference depending on Func1's declaration Func2(&A); // Passes a pointer to A // at the end of this function, the scope will end and A will automatically be destroyed}
Now with this function, every time another function calls foo, A will be created and then destroyed when the function exits. Not bad right. What about this?void foo(){ // Object A of class CSomeClass has been declared inside the scope of foo CSomeClass *A = new CSomeClass; // do some stuff .... // you can even call other functions and use A as a parameter Func1(*A); // This could be pass by value or pass by reference depending on Func1's declaration Func2(A); // Passes pointer A of CSomeClass (Edited) // MEMORY LEAK // at the end of this function, the scope will end, but A was created on the heap // delete should be called here}
So with dynamic memory allocations, you must free the memory. So why you might ask do we even need dynamic memory allocations? Well one, to declare variables on the stack, you need to know exactly what you'll need at compile time. If you want to be able to create arrays of various sizes depending on user input, or if you're making a game and want to load variable amount of resources, you'll need to use dynamic memory allocations. Take this example:int num_students;// First get the number of students in the classstd::cout << "How many students are in the class?"std::cin >> num_students;// Create a dynamic students arrayCStudent *student_array = new CStudent[num_students];// Do some stuff with the data....// call the array version of delete to free memorydelete [] student_array;

In the previous situation, you must use dynamic memory because the size of the array is determined by the user. How can smart pointers help?



Smart Pointers


(chief reference: Smart Pointers (Modern C++) on MSDN)



Smart pointers allow you to create dynamic memory allocations but defined them inside a scope or an owner. This way, when the owner goes out of focus, the data will be automatically deleted. Smart pointers have been implemented using templates and to use them, you must include the header . Smart pointers are in the std namespace. I will only discuss unique_ptr's here. Later, I may talk about the other types of smart pointers in between updates to "A Complete Graphicsless Game"

So how do you create a unique_ptr?
std::unique_ptr apples(new Base(L"apples")); // Where Base is the class type
You create a unique_ptr like a typical template and then pass the raw pointer to initialize the variable. After that, you can use the unique_ptr, just as you would any other pointer.class Base{ public: Base(const std::wstring &string) :m_string(string) { } virtual void Display() const { std::wcout << L"Base:" << m_string << std::endl; } private: std::wstring m_string;};int main(){ // declare some unique_ptrs. This pointers can have only one owner and cannot be copied. Only moved. std::unique_ptr apples(new Base(L"apples")); apples->Display();}
unique_ptr's can also be passed to other functions, but you must pass by reference. Passing by value will result in a compiler error. With unique_ptr's, only one can own the pointer, but if you pass by value you will make a copy of the unique_ptr which in essence makes two unique_ptr's that own the same block of memory.

You can also use unique_ptr's with derived class and virtual functions and get the typical C++ behavior.class Base{ public: Base(const std::wstring &string) :m_string(string) { } virtual void Display() const { std::wcout << L"Base:" << m_string << std::endl; } private: std::wstring m_string;};class Derived : public Base{ public: Derived(const std::wstring &string) :Base(string) { } virtual void Display() const { std::wcout << L"Derived:::"; __super::Display(); // __super is MS specific. Others should use Base::Display(); }};int main(){ // declare some unique_ptrs. This pointers can have only one owner and cannot be copied. Only moved. std::unique_ptr apples(new Base(L"apples")); std::unique_ptr oranges(new Derived(L"oranges")); apples->Display(); oranges->Display();}
This is very useful when dealing with vectors as the next example show.std::vector > test_vector;test_vector.push_back(std::unique_ptr(new Base(L"apples")));test_vector.push_back(std::unique_ptr(new Derived(L"oranges")));
In the above example, you can use the vector of unique_ptr's in the same way you would if it was a vector of raw Base pointers, but there is one nice benefit. If this vector had raw pointers, you'd have to make sure you manual free the pointers before you clear the vector or erase an element, but with unique_ptr's, all of that is handled for you.

Conclusion


I hope this information was helpful. I am in no way an expert so if you anyone sees something glaring that I missed, feel free to leave a "kind" comment. If you would like to know more about smart pointers, I suggest checking out the like on msdn.

10
Sign in to follow this  
Followers 0


15 Comments


Sorry. I tried editing this on my cell and it messed up all my code blocks. I'll fix the rest when I get home and on a proper computer

 

Edit: Fixed

0

Share this comment


Link to comment

It should be mentioned that __super is MS specific.

1

Share this comment


Link to comment

in your second foo(), &A returns a pointer to a pointer to CSomeClass, not a pointer to CSomeClass. should be Func2(A).

1

Share this comment


Link to comment

in your second foo(), &A returns a pointer to a pointer to CSomeClass, not a pointer to CSomeClass. should be Func2(A).

 

Thanks for mentioning that. I think I had just copied and pasted from the first function and forgot to change it. I'll edit the code and I'll add a comment regarding __super.

0

Share this comment


Link to comment

Thanks for the write up on pointers. I haven't used smart pointers before and have never had the motivation to read up on them. This was perfect for a crash course on the subject, thanks!

1

Share this comment


Link to comment

Are Smart Pointers in widespread use in gaming studios? Or do professionals prefer normal pointers?

0

Share this comment


Link to comment

I have the same question as Tispe. Also I viewed the vid and, to me at least, It seems to have a good setup for a story. I say continue the project.

0

Share this comment


Link to comment

I don't know if the "official" Smart Pointers from the Standard Library are used often, but it is common practice to let the release of a memory block pointed by a raw pointer be handled by some RAII-based wrapper.

0

Share this comment


Link to comment

Are Smart Pointers in widespread use in gaming studios? Or do professionals prefer normal pointers?

 

If I were you, I think this question could best be answered on the normal forums. You'd probably get more responses. I'm not currently working at a studio so I can't answer this.

1

Share this comment


Link to comment

It's also worth pointing out that one of the primary motivators for scoped/smart ptrs is to handle correct resource disposal in the presence of exceptions. The new/delete idiom tends to break very easily when exceptions are in play, and writing exception-safe code with raw pointers is extremely challenging.

2

Share this comment


Link to comment
I think there was a bug in the system. I just updatedsome information and it got added as new. I don't know why and didn't expect it.
1

Share this comment


Link to comment

One thing of note is that you likely want to be using std::make_unique() when creating unique pointers. They were the first inclusion in C++14 and supported by most compilers now, but even if you are using an environment where it is not available you can easily add the function. For reference see: http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique

 

Also note in your vector example it would be much better to use test_vector.emplace_back() instead of push_back().

1

Share this comment


Link to comment

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