3

I have a structure of the following type:

struct SPacket
{
    unsigned char payload[260]; 
    unsigned int payloadLength; 
}; 

I have a pointer object to this structure:

SPacket* ptrObj; 

how can I perform a deep copy of ptrObj into a another object:

SPacket obj;  
1

2 Answers 2

8

The compiler-generated copy constructor will deep-copy the array member, so just use it:

SPacket obj(*ptrObj);
Sign up to request clarification or add additional context in comments.

4 Comments

+1 but probably important to note, this is only correct for fixed size array's not allocated on the heap.
Error, no match for operator *
@jaycode: If you're receiving that error, you probably don't have a pointer :)
I can confirm. When the ptrObj is a reference (internally just a pointer) then there should be no asterisk.
3

The solution is extremely simple: use the copy constructor:

SPacket obj = *ptrObj;

This will call the (implicit) copy constructor.

7 Comments

Thus would work in C too, no (after adding a struct)?
@juanchopanza I guess yes, it would. What I meant by the intro, is that the copy constructor should be the first thought
But the solution is also extremely simple in C.
@juanchopanza in this case, yes, it's the same. But if you have pointers inside the type you would need a copy/clone function.
Then you would have to implement a copy constructor in C++ anyway.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.