Sid
Sid

Reputation: 43

overloading assignment operator without using =

I was asked a question in an interview.

Is there a way that you can assign the value of one user-defined object to another user-defined object without using = operator.

Basically, he asked me to overload the assignment operator for the class such that overloaded assignment operator in-turn won't use primitive types = operator.

Is memcpy a correct approach?

Upvotes: 2

Views: 368

Answers (1)

user4581301
user4581301

Reputation: 33932

Question asked: Is memcpy a correct approach? Not always.

Question implied: overloading assignment operator without using =? Use the Copy and Swap Idiom.

I'll demonstrate the implied question by explaining why the asked question's answer is No.

memcpy performs a binary copy without applying any context to the nature of the variables in the object being copied. It can be exceptionally dangerous and can only be used on objects which are trivially copyable.

Consider the following case:

struct A
{
    int buffersize;
    char * buffer;
    A(int size):buffersize(size), buffer(new char[buffersize])
    {
    }
    A(const A& source):buffersize(source.buffersize), buffer(new char[buffersize])
    {
        memcpy(buffer, source.buffer, buffersize);
    }
    ~A()
    {
        delete[] buffer;
    }
    A& operator=(A source) // Assignment via Copy and Swap Idiom
    {
        std::swap(buffersize, source.buffersize);
        std::swap(buffer, source.buffer);
    }
}

This example is very stupid and very simple. Anyone sane would use std::vector, but it does implement the Rule of Three (What is The Rule of Three?) so that it is safe to copy while not being trivially copyable.

See the work being performed in the copy constructor? This will not be performed by memcpy. memcpy will copy the value of buffer, the address, and leave you with two objects pointing to the same buffer. If the sharing of the buffer doesn't prove fatal sooner, eventually both destructors will have to run and buffer will be freed twice.

Note memcpy IS being used to copy the internal buffer. The buffer is an array of plain old data (POD) that is trivially copyable. If it was not trivially copyable, πάντα ῥεῖ's suggestion of std::copy should be followed. We should use std:::copy in either case so that the code is more easily modified in the future, but then the example doesn't show a safe use of memcpy.

Upvotes: 3

Related Questions