Reputation: 7044
I have 2 class:
class Request
{
KeyValuePair* dimension;
};
class Response
{
KeyValuePair* dimension;
};
class KeyValuePair
{
public:
hash_map<string, string> hmap;
};
in one of the method, I want to populate the Response.dimension
with Request.dimension
but I want the Request.dimension
pointing to a different address from Response.dimension
?
I don't want any change Response.dimension
which also affect Request.dimension
.
Is there a way to do that?
void Transformation::applyTransformations(const Request& req, Response& res)
{
res.dimension = req.dimension; // WRONG. Pointing the same address.
}
Upvotes: 1
Views: 7405
Reputation: 60004
You could implement a 'copy on write' pointer, to avoid unneeded overhead.
Upvotes: 0
Reputation: 70931
You need to allocate new memory. Also you need to have copy constructor(or use the default one if appropriate).
res.dimension = new KeyValuePair(req.dimension);
Also you will have to handle the memory i.e. define a copy constructor, copy operator, empty constructor and destructor.
Upvotes: 0
Reputation: 206508
You can overload the =
operator of your Response
class to perform a deep copy of the request.dimension
, this will make your Response.dimension
have same value as that of Request.dimension
and yet will be independent of any changes to Request.dimension
.
Upvotes: 1
Reputation: 258558
Yes, of course:
*(res.dimension) = *(req.dimension);
Note that if KeyValuePair
is not a POD type, you should define the assignment operator (operator =
), as it will get called during the assignment. If you don't, the compiler-generated one will be called.
You should also check if res.dimension
is properly allocated, if not, use the copy constructor:
if ( res.dimension )
*(res.dimension) = *(req.dimension);
else
res.dimension = new KeyValuePair(*(req.dimension));
Upvotes: 2