I have a iNode
class which has a member _nodeState
. The functions outside of the class want to access the member _nodeState
. So I need to design a getState
function in iNode
class to pass this information. _nodeState
is dynamically allocated before the getState
function called. I want to use iSharedPtr<iStateHash>
for _nodeState instead of raw pointer. However, the current implementation of iStateHash
is of "intrusive pointer" type, so I have to use raw pointer for _nodeState
.
class iNode{
public: return_type getState(input_type){}
void initializeState(){_nodeState = new iStateHash;}
private:
typedef iHashMap<int ikey, iSharedPtr<iValue>> iStateHash;
iStateHash* _nodeState;
};
Since the _nodeState points to a large amount of data, passing by pointer or passing by reference seems to be better than passing by value.
If it's passing by reference, then the return_type
of the getState
function should be reference type (const reference return seems not be recommended after c++11). So I have the design 1:
iStateHash* & iNode::getState(){return _nodeState;}
So in a block outside of the class:
iNode newNode;
newNode.initializeState();
iStateHash &myNodeState = newNode.getState();
If it's passing by pointer, then could return a pointer or set a pointer as the function argument:
iStateHash * iNode::getState(){return _nodeState;}
or
void iNode::getState(iStateHash* outputState){outputState = _nodeState;}
then
iNode newNode;
newNode.initializeState();
iStateHash *myNodeState = NULL;
getState(myNodeState);
Since shared pointer cannot be used in this case, the raw pointer usage is not recommended? Or if the raw pointer is still better than returning a reference?
Or is there a better way to get the _nodeState
information outside of the class?
Moreover, how about using iStateHash _nodeState;
as a member variable instead of using a pointer type (iStateHash* _nodeState;
)? This would be better?