c++memoryfactory

How is it possible to emplace construct an object from a factory function?


Is it possible to emplace construct an object from a factory function ?

std::mutex f() {return std::mutex{};} // factory function using guarenteed copy elision allows this even though mutex cannot be copied or moved from

int main() {
  std::optional<std::mutex> m;
  m.emplace(f()); // <-- how is this possible somehow ? what type of wrapper object should we use ?
}

The best answer will give multiple ideas/ work arounds.


Solution

  • A simple wrapper with conversion operator does the job:

    struct Wrapper
    {
        operator std::mutex() { return f(); };
    };
    
    m.emplace(Wrapper());
    

    Demo

    Demo with anonymous struct