jeudi 26 août 2021

Builder pattern with struct

I'm trying to implement a builder patter in C++. That what i got by now:

struct Person {
  std::string name;
  uint32_t age;
  std::vector<std::string> pet_names;
};


class PersonBuilder {
public:
  PersonBuilder& SetName(std::string name) {
    person_.name = std::move(name);
    return *this;
  }

  PersonBuilder& SetAge(uint32_t age) {
    person_.age = age;
    return *this;
  }

  PersonBuilder& SetPetNames(std::vector<std::string> pet_names) {
    person_.pet_names = std::move(pet_names);
    return *this;
  }

  Person Build() {
    return Person(std::move(person_));
  }

private:
  Person person_;
};

int main() {
  auto person = PersonBuilder()
      .SetName("John")
      .SetAge(23)
      .SetPetNames({"rax", "rbx", "rcx"})
      .Build();

  return EXIT_SUCCESS;
}

I'm a little worried about unitilized uint32, and std::move(person_) inside a Build method. Am i doing it right or there is a better way, with a struct constructor for example?

Aucun commentaire:

Enregistrer un commentaire