Jump to content

  • Log In with Google      Sign In   
  • Create Account


std::shared_ptr and inheritance


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 Tispe   Members   -  Reputation: 1024

Like
0Likes
Like

Posted 26 January 2014 - 10:59 AM

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?



Sponsor:

#2 rip-off   Moderators   -  Reputation: 8121

Like
0Likes
Like

Posted 26 January 2014 - 11:11 AM

Have you tried Googling for something like shared_ptr dynamic_cast?

 

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?



#3 Bregma   Crossbones+   -  Reputation: 5018

Like
3Likes
Like

Posted 26 January 2014 - 11:17 AM

Sounds like you're trying to downcast the shared pointer.  That's usually a code smell that you've got a bad design, and you're subverting a nominally OO structure to force procedural methodology.

Edited by Bregma, 26 January 2014 - 11:19 AM.

Stephen M. Webb
Professional Free Software Developer

#4 SeanMiddleditch   Members   -  Reputation: 5189

Like
4Likes
Like

Posted 26 January 2014 - 02:03 PM

As a complete aside, shared_ptr is almost certainly wrong here.  What is shared about the ownership of the messages?  The message sender gives the message to the messaging system.  Then the messaging system gives the message to the handler.  There's only one proper owner at every point in the chain.  Use unique_ptr instead.

 

shared_ptr is usually completely wrong.  Shared ownership semantics are a cop-out for when you don't want to think through the ownership cycle of your data.  Use shared_ptr as your last resort only... and maybe not even then.  (I have a strict ban on shared_ptr in my personal codebases after seeing the damage wrought by use of it in some big commercial codebases.  The few places truly needing shared ownership semantics are often best served by custom handles tailored to the situation, if for no other reason than being able to add back-reference support to debug builds so you can track down what object is holding on to the shared resource and keeping it alive.)



#5 Tispe   Members   -  Reputation: 1024

Like
0Likes
Like

Posted 26 January 2014 - 03:30 PM


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.



#6 rip-off   Moderators   -  Reputation: 8121

Like
2Likes
Like

Posted 26 January 2014 - 04:31 PM


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, 26 January 2014 - 04:33 PM.


#7 Tispe   Members   -  Reputation: 1024

Like
0Likes
Like

Posted 27 January 2014 - 12:50 AM

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, 27 January 2014 - 03:47 AM.


#8 cdoubleplusgood   Members   -  Reputation: 824

Like
1Likes
Like

Posted 27 January 2014 - 05:10 AM

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.



#9 Juliean   GDNet+   -  Reputation: 2438

Like
1Likes
Like

Posted 27 January 2014 - 05:58 AM

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, 27 January 2014 - 06:01 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS