C GotW - yszheda/wiki GitHub Wiki

GotW #90 Solution: Factories

https://herbsutter.com/2013/05/30/gotw-90-solution-factories/

widget* load_widget( widget::id desired );
  • Assuming that widget is a polymorphic type, what is the recommended return type?

polymorphic->reference/pointer->raw pointer may lead to mem leak or dangling pointer->smart pointer(unique_ptr or shared_ptr)

  • If widget is not a polymorphic type, what is the recommended return type?

Of course pass-by-value! The caller can use move to avoid heavy copy cost.


Note the use of std::optional

// Example 4(c): Alternative if not returning an object is normal
//
optional<vector<gadget>> load_gadgets() noexcept {
    vector<gadget> ret;
    // ... populate ret ...
    if( success )            // return vector (might be empty)
        return move(ret);    // note: move() here to avoid a silent copy
    else
        return {};           // not returning anything
}

// Calling code (exception-safe)
auto v = load_gadgets();
if(v) use(*v);

How if (v) works?

constexpr explicit optional<T>::operator bool() const noexcept;
⚠️ **GitHub.com Fallback** ⚠️