c++option-typefolly

How does copy assignment work in for folly::Optional<T>?


I was reading the code in folly::Optional for copy assignment and I am not clear how exactly the call to construct() assigns a value to the optional. Specifically in construct() how does this expression work?

new (const_cast<void*>(ptr)) Value(std::forward<Args>(args)...);

Solution

  • To deconstruct the line you wrote:

    std::forward<Args>(args)... is performing variadic-template perfect forwarding. In essence, it means that whatever was an r-value will be forwarded to, and so on, for any number of arguments.

    Value(std::forward<Args>(args)...) is calling the constructor of Value on these arguments.

    new (const_cast<void*>(ptr)) ... is calling placement new.

    So what the line is saying is, create an object at this specific memory location, constructing the object there by forwarding all the arguments you got.