I recently find a code snippet as follows:
// To be specific: the "Item" can be viewed as "std::pair<xxx, xxx>*" here
void moveItemDuringRehash(Item* itemAddr, Item& src) {
// This is basically *itemAddr = src; src = nullptr, but allowing
// for fancy pointers.
// TODO(T31574848): clean up assume-s used to optimize placement new
assume(itemAddr != nullptr);
new (itemAddr) Item{std::move(src)};
src = nullptr;
src.~Item();
}
The code is originated from the Folly Lib of Facebook. The functionality of this code is simple: copy std::pair*
referenced by src
to the memory pointed by itemAddr
.
The implementation should be very simple, as mentioned in the comment. But actually, the code does not. The new
operator with std::move
is confusing, and I am not sure what is happening under the hood. I guess. Item{std::move(src)}
construct a temp object with move ctor of std::pair*
. And the temp object is copy to the object pointed by itemAddr by copy ctor of std::pair*
. I am not sure if my guess is correct. Thank you for sharing your opinion. By the way, I was wondering if there is any performance benefit from this new operator with std::move
.
Another question is why src.~Item()
is needed? For safety, I need to set src
(std::pair*
) to nullptr
. But why I need to use src.~Item()
to dtor a nullptr
?
Aucun commentaire:
Enregistrer un commentaire