在实时关键代码中返回多态对象

问题描述 投票:0回答:1

在 C++ 中是否可以让函数以实时安全的方式返回多态对象?

对于上下文:我想实现一个返回有关系统中检测到的错误的信息的函数。我的第一个天真的方法是像这样实现它(简化):

class Error { ... };  // abstract base class
// different error cases:
class FooError: public Error { public: FooError(int foo) {...}};
class BarError: public Error { public: BarError(int bar, float baz) {...}};

// check if there is an error and return the first one detected
std::shared_ptr<Error> get_error() {
    if (is_error_foo()) {
        return std::make_shared<FooError>(42);
    }
    if (is_error_bar()) {
        return std::make_shared<BarError>(13, 3.14);
    }

    ...
}

现在的问题是代码是针对实时关键系统的,因此不应该使用动态内存分配。因此我不应该使用shared_ptr。 是否有另一种方法来实现上述不使用动态内存分配(或其他不应该在实时代码中完成的事情)?

c++ polymorphism real-time
1个回答
1
投票

当您不需要运行时多态性时,不要使用运行时多态性。 (公共)继承并不是解决所有问题的方法,不要将其作为您的首选。我基本上看到了两种避免动态分配的方法:

  • std::variant<FooError,BarError>
    不动态分配内存
  • 仅保留
    Error
    std::string message
    ,并让
    get_error
    根据错误条件构建该字符串。通常,最终您需要的只是一条错误消息。如果您需要更多信息,请考虑将其编码为枚举成员,例如
    enum ErrorType {Foo,Base};
© www.soinside.com 2019 - 2024. All rights reserved.