lundi 23 décembre 2019

When operator overloading, does the GNU compiler do an initial evaluation of the assignment, prior to evaluating the overloaded operator?

Let me explain.

I am writing a message structure in which I would like to pass character arrays into and out of an object, but store them internally as void pointers. Furthermore, I want to use operator overloading so that the operation is opaque to the user. Below, is the first pass at it

struct Msg
{
    const void* body;

    Msg() : body(new void*[100]) {}

    const void* operator = (char* rhs)
    {
        void* output = new void*[sizeof(rhs)];
        memcpy(output, rhs, sizeof(output));
        return output;
    }

    char* operator = (const void* rhs)
    {
        char* output = new char[sizeof(rhs)];
        memcpy(output, reinterpret_cast<char*>(rhs), sizeof(output));
        return output;
    }
};

The first overload works. The second overload does not work. I want to be able to do something like this.

Msg msg;
msg.body = "test message.";

char* newMsg = new char[sizeof(Msg)];
newMsg = msg.body;

It seems what is happening is that the compiler is evaluating the assignment prior to evaluating the overloading. Am I correct in this assumption, and is there a way to avoid this?

Aucun commentaire:

Enregistrer un commentaire