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

std::shared_ptr and inheritance

8 posts in this topic

Hello, I am building a message system that stores commands in a STL container. The messages have a base struct but uses shared pointers to derived structs that are then placed in the container.

 

I have trouble with using a base struct and placing a shared pointer to a derives struct on a STL container and then retrieving the shared pointer to the derived class.

struct SystemUpdate
{
	DWORD UpdateType;
};

struct SystemDisplayUpdate : SystemUpdate
{
	DisplaySettings NewSettings;
};

struct SystemInstructions
{
	std::queue<std::shared_ptr<SystemUpdate> > SystemUpdates;
};
while(!System.SystemUpdates.empty()){
		switch(System.SystemUpdates.front()->UpdateType){
			case 0x00:
				{
					std::shared_ptr<SystemDisplayUpdate> spDisplayUpdate = System.SystemUpdates.front();
				}
				break;
			case 0x01:
				{
				}
				break;
			default:
				break;
		}

		System.SystemUpdates.pop();
	}

The compiler gives the following error:

error C2440: 'initializing' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'std::tr1::shared_ptr<_Ty>'

 

I think it is because the container stores a shared pointer to the base struct, but I want to have a new shared pointer to the derived struct, which was the original shared pointer format placed on the container.

 

How do I properly cast between shared pointers using inheritance?

0

Share this post


Link to post
Share on other sites

Have you tried Googling for something like [url="https://encrypted.google.com/search?q=shared_ptr+dynamic_cast"]shared_ptr dynamic_cast[/url]?

 

Of course, there is the question as to why you're client code needs to care about the actual type. Is adding a virtual member function not an option?

0

Share this post


Link to post
Share on other sites


Of course, there is the question as to why you're client code needs to care about the actual type. Is adding a virtual member function not an option?

 

I don't follow your suggestion. I have a block of data on the heap and the DWORD UpdateType at the beginning helps me figure out later what to do with that block of data. I am trying to avoid leaks by using a shared_ptr to the block, which I will probably swap out with a unique_ptr when I get it working.

 

I use inheritance such that I can reuse the container for many different types of derivatives. That way the commands and vary in size and be command specific, just by adding more derivatives.

 

I'm guessing you all know my intentions with this code, and I fail to see how it is a bad design.

0

Share this post


Link to post
Share on other sites

I'm guessing you all know my intentions with this code...

I could be wrong, but this looks suspiciously close to a common so-called "anti pattern" that I will describe in a second.

 

 


... and I fail to see how it is a bad design.

A design that requires down-casting is generally considered to be poorer than one that avoids it.

 

The general anti-pattern that this appears to be similar to is one where each sub-class has some unique identifier (either stored in a member or returned by a virtual member function), and this identifier is used to determine the type of the sub-class. A cast is performed, and some logic specific to that type can then be run.

 

If that is the case, then an alternative approach that avoids the identifier and the cast is to have a virtual method in the base class, with the sub-class specific logic contained within each derived class:

struct SystemUpdate
{
    virtual ~SystemUpdate() {}
 
    virtual void RunUpdate(/* Parameters? */) = 0;
};
 
struct SystemDisplayUpdate : SystemUpdate
{
    DisplaySettings NewSettings;
 
    virtual void RunUpdate(/* Parameters? */) {
         // Apply NewSettings...
    }
};
 

while(!System.SystemUpdates.empty()){
    System.SystemUpdates.front()->RunUpdate(/* ... */);
    System.SystemUpdates.pop();
}

As I said, this is a superficial similarity, I'm not familiar with your codebase. I am curious as to how your system might be different from this pattern, or why you don't want to use a virtual function if it is quite similar.

 

Indeed, whether this is a "good" design depends on how this is used and what other classes are derived from the base class. But I'd personally prefer this type of solution over one with a set of magic UpdateType values (or even one with named constants), all other things being equal.

Edited by rip-off
2

Share this post


Link to post
Share on other sites

I want not only the GUI to use this command system, also a peer can give commands to the game (going through some filtering first).

 

Say for example that this game connects to a server and that server needs to send a packet to the game to spawn a player.

 

The client recieves a block of data from a packet. Now we need to inspect the contents of that block in order to determine what to do.

struct SystemSpawnNewPlayer : SystemUpdate
{
	DWORD PlayerID;
	float Pos[3];
};

struct SystemUpdatePlayer : SystemUpdate
{
	DWORD PlayerID;
	float Pos[3];
};

struct SystemDeletePlayer : SystemUpdate
{
	DWORD PlayerID;
};

Downcasting in this manner; to me seems legit.

 

 

It looks like that std::dynamic_pointer_cast<> is the way to go. However I can't find an equivalent for std::unique_ptr.

 

 

 

Example from msdn:

#include <memory> 
#include <iostream> 
 
struct base 
    { 
    virtual ~base() 
        { 
        } 
 
    int val; 
    }; 
 
struct derived 
    : public base 
    { 
    }; 
 
int main() 
    { 
    std::shared_ptr<base> sp0(new derived); 
    std::shared_ptr<derived> sp1 = 
        std::dynamic_pointer_cast<derived>(sp0); 
 
    sp0->val = 3; 
    std::cout << "sp1->val == " << sp1->val << std::endl; 
 
    return (0); 
    } 
Edited by Tispe
0

Share this post


Link to post
Share on other sites

It looks like that std::dynamic_pointer_cast<> is the way to go. However I can't find an equivalent for std::unique_ptr.

 
There is no equivalent for unique_ptr.
It is not possible to define a consistent behavior of such a cast. If the cast succeeds, a new pointer is returned, and the original pointer must be nullptr then (because there can be only one). What if the cast fails: Would the original pointer be nullptr or not?
However, if you absolutely need it, you can code a dynamic_cast for unique_ptr by yourself. Just remember to document it well, cause in 4 weeks you will have forgotten because it's so counter-intuitive...
 
But in general it would be best to avoid the downcast completely, as the other guys already suggested. Have you considered using double dispatch? This idiom has helped me more than once avoiding downcasts.

1

Share this post


Link to post
Share on other sites

I do agree with the OOP that downcasting here really is probably at least a viable option. Of course, double dispatch could be used:

struct SystemSpawnNewPlayer : SystemUpdate
{
        DWORD PlayerID;
        float Pos[3];

        Process(Processer& processer) override
        {
                   processer.ProcessPlayerSpawn(*this);
        }
}

class Processer
{
public:
            
       void ProcessPlayerSpawn(SystemSpawnNewPlayer& spawnPlayer);
      void ProccesUpdatePlayer(SystemUpdatePlayer& updatePlayer);
}

But this would probably get tedious very quickly. However there is method for (almost, I'll get to that) safe down-casting, which requires templates:

/*******************************
* BaseMessage
*******************************/

/// Used for implementing the CRTP for messages
/** This class is used as a base from which the actual message derives.
*   It offers an implementation of the Curiously recurring template pattern,
*   by storing a static message counter. Each different message struct
*   will increase this counter and aquire its unique id from it. It also offers
*   a method to quickly convert a derived message to its underlying type.*/
struct BaseMessage
{
protected:
	typedef unsigned int Family;
public:
	Family m_family; ///< The messages current family id

	/** Converts message to an underlying type.
	 *  This method trys to convert the message to the
	 *  templated type, using the internal type id. If the
	 *  types doesn't fit, a \c nullptr is returned.
	 *  
	 *  @tparam M The target messages type.
	 *
	 *  @return Pointer to the message, now with its converted type.
	 */
	template<typename M>
	const M* Convert(void) const;

protected:
	static Family GenerateFamilyId(void);

private:
	static Family family_count; /**< Counter of instanciated messages.
		*   Each message of a different type that is created, or whose 
		*   family function is called the first time will increase this 
		*   counter. The counter is used as the ID of the next message. */
};

template<typename M>
const M* BaseMessage::Convert(void) const
{
	if(m_family == M::family())
		return static_cast<const M*>(this);
	else 
		return nullptr;
}

/*******************************
* Message
*******************************/

/// The message parent struct
/** Each message must derive from this struct. It automatically sets its
*   unique family id on creation, which can then be accessed via a static
*   method, so you can compare the type of a message object with the type
*   of a message struct. */
template <typename Derived>
struct Message : 
	public BaseMessage
{
public: 

	Message(void) 
	{
		m_family = family(); 
	};

	/** Returns the "family" type of the message.
	 *	This method sets the type id for the specific message struct on
	 *  the first call, and returns it from there on. The id is consistent 
	 *  between the running time of a program and cannot be altered, but
	 *  it may alter between different runs, depending on the first creation 
	 *  order of the messages. 
	 *
	 *  @return The unique id of this message instance
	 */
	static Family family(void)
	{
		static BaseMessage::Family Family = BaseMessage::GenerateFamilyId();
		return Family;
	}
};

This allows you to specify messages like this:

// you'd need to rename that base classes though

struct SystemSpawnNewPlayer : SystemUpdate<SystemSpawnNewPlayer>
{
        DWORD PlayerID;
        float Pos[3];
}

// and this is how to use it:

std::unique_ptr<SystemUpdate> update; // gets set somewhere between...
....

// or, you could use a switch-statement using update.m_family
if(SystemSpawnNewPlayer pSpawnPlayer = update->Convert<SystemSpawnNewPlayer>())
{
...
}
else if(SystemUpdatePlayer pUpdatePlayer = update->Convert<SystemUpdatePlayer >()
{
...
}

Every message now has its own unique ID, both the instances as well as the class type(!) itself. As you can see in the Convert-method, this allows you to downcast using just a static_cast, and safe in a way (except for when you specify the wrong class in the template brackets when inheriting SystemUpdate<...>. You might consider it an option.

Edited by Juliean
1

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