• entries
101
122
• views
58299

# shared_ptr

139 views

I've been reading through Game Coding Complete, 2nd Ed. by Mike McShaffry, and it's a very excellent book. A little disappointed it uses DirectX - i've been developing with SDL and OpenGL, but I knew that going in. I'm a couple of hundred pages in and feel that I definitely got my money's worth.

For one thing, it's finally convinced me to get over my stubborness, and i've finally looked into Boost (really have been meaning to do so before, but have been procrastinating.

The book's section on boost::shared_ptr has convinced me that shared_ptr really is a good thing - especially using std::list< boost::shared_ptr > rather than std::list.

Previously every time I had been using a container with pointers I had encapsulated the container in a manager class to prevent memory leaks, which I had considered less than ideal.

One thought has come up though (i'll probably ask this in the forums if no one has any suggestions here). I also changed the books example to use std::string rather than char* in the shared_ptr example.
class CPrintable{    char *m_Name;public:    CPrintable(char* name) {m_name = name;}    // other functions here, including a destructor}// toclass CMyPrintable{    std::string m_Name;public:    CMyPrintable(std::string name) {m_Name = name;}}

Anyways, this raises the question of using std::string in a constructor. I need to look into it, but what happens if m_Name = name fails (lack of memory would be my best guess of how it could happen) - and do I need to worry about it with char *m_Name as well? Perhaps I shouldn't be giving a value to m_Name in the constructor? Perhaps do it in an init function that can return a value indicating success or failure?

Anyways, switching over to string also let me extend the example to also use boost::lexical_cast so that the output was a little more informative of what is going on. I had previously been using stringstream for converting between ints and strings, but lexical_cast makes my code shorter and easier to read.

Also, it's not really covered that much in this book, but I think it's time I got more comfortable with C++ exceptions. It's one of those things that I really should be making an effort to get comfortable with (templates are also on my list). Like Boost, they are something that I just haven't absolutely needed so far, but I suspect using them would make life better.

There are no comments to display.

## Create an account

Register a new account