Не могли бы вы использовать интерфейс и полиморфизм для расширения этого
Плюсы
Минусы
Мне кажется, что для этого конкретного случая один оператор if
и логический флаг - лучший вариант, но не все со мной согласны.
Что вы думаете?
Исходный
// Connects to a local pipe, and naturally
// owns that connection
struct CommandWriter
{
CommandWriter() {
fd = open("/path/to/fifo", O_WRONLY);
if (fd == -1)
throw std::runtime_error("Could not establish connection to FIFO");
};
~CommandWriter() {
close(fd);
};
// (Has useful member functions here)
private:
CommandWriter(CommandWriter const&); // Not relevant to question
int fd;
};
Расширенный с логическим флагом
// Adds a constructor where an FD can be specified
// from the call site, and no ownership is taken
struct CommandWriter
{
CommandWriter() : owns_fd(true) {
fd = open("/path/to/fifo", O_WRONLY);
if (fd == -1)
throw std::runtime_error("Could not establish connection to FIFO");
};
CommandWriter(int fd) : fd(fd), owns_fd(false) {};
~CommandWriter() {
if (owns_fd)
close(fd);
};
// (Has useful member functions here)
private:
CommandWriter(CommandWriter const&); // Not relevant to question
int fd;
bool owns_fd;
};
Расширенный с полиморфизмом
// Sorry for the poor type names!
struct ICommandWriter
{
virtual ICommandWriter() {}
// (Has useful member functions here)
private:
ICommandWriter(ICommandWriter const&); // Not relevant to question
};
struct CommandWriter_Connects : ICommandWriter
{
CommandWriter_Connects() {
fd = open("/path/to/fifo", O_WRONLY);
if (fd == -1)
throw std::runtime_error("Could not establish connection to FIFO");
};
~CommandWriter_Connects() {
close(fd);
};
// (Has useful member functions here)
private:
int fd;
};
struct CommandWriter_Uses : ICommandWriter
{
CommandWriter_Uses(int fd) : fd(fd) {};
~CommandWriter_Uses() {};
// (Has useful member functions here)
private:
int fd;
};
]