memcpy writing to an object of type ‘class uint256’

Viewed 1039

Well, this is probably a really simple warning to fix, but I didn't figure it out yet. Some time ago, I made an update for my uint256 class, and after that, I get this warning:

base58.h:261:52: warning: ‘void* memcpy(void*, const void*, size_t)’ writing to an object of type ‘class uint256’ with no trivial copy-assignment; use copy-assignment or copy-initialization instead [-Wclass-memaccess]
         memcpy(&id, &vchData[0], HASH_LEN_BYTES);

This is the function where is the memcpy:

bool GetKeyID(CKeyID &keyID) const {
    if (!IsValid())
        return false;
    switch (nVersion) {
    case PUBKEY_ADDRESS:
    case PUBKEY_ADDRESS_TEST: {
        uint256 id;
        memcpy(&id, &vchData[0], HASH_LEN_BYTES);
        keyID = CKeyID(id);
        return true;
    }
    default: return false;
    }
}

This is my uint256 class: uint256.h

2 Answers

You have defined a copy-assignment for base_uint<N> class here

And a copy constructor for base_uint here, and a conversion constructor uint256 here

Also if you simply cast your (uint256*) argument to (void*) the warning will disapear, and you will have the expected behavior, but that's not the recommended way to do, because it may break silently in the future if you really make something different in the assignment. I think the best is to remove those copy constructors, and assignment operator. The only operator that would be interesting in my view is a conversion between base_uint of different widths.

There are two alternative solutions:

  • Make the class trivially copyable.
  • Do not attempt to memcpy the class.

how i can replace memcpy on this context?

Write a constructor accepting whatever vchData is as an argument.

how i can make the class trivially copyable?

Remove copy constructor and any members / bases that are not trivially copyable.

Related