LINUX.ORG.RU

Паттерн Builder в C++

 , ,


0

2

Является ли нижеприведенный код корректным кодом C++ и не содержит ли UB?

struct MyObject {
    int a;
    int b;
};

class MyObjectBuilder {
    int m_a = 0;
    int m_b = 0;
public:
    MyObjectBuilder &a(int value) {
        m_a = value;
        return *this;
    }
    MyObjectBuilder &b(int value) {
        m_b = value;
        return *this;
    }
    MyObject build() {
        return MyObject { m_a, m_b };
    }
};

MyObject f() {
    return MyObjectBuilder().a(10).b(20).build();
}

(меня напрягает возврат ссылки на this из метода объекта, когда сам объект является временным)

★★★★★

Последнее исправление: KivApple (всего исправлений: 1)

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.

https://en.cppreference.com/w/cpp/language/lifetime

Пока цепочка вызовов не закончится, деструктор не будет вызван, так что всё ок. Такие штуки много где втречаются, вроде норм работают.

Ivan_qrt ★★★★★
()
Ответ на: комментарий от no-dashi-v2

Ну смущает его не то, что он возвращает из f() (там понятно copy elision, всё нормально), а ссылка, возвращаемая из временного MyObjectBuilder() при вызове a(). Если MyObjectBuilder() уничтожится до вызова b(), то будет плохо. В этом и был вопрос.

Ivan_qrt ★★★★★
()