Coding Patterns

Static variables for header-only releases

Note: As of v.10.1.1, this pattern is still used, but it is no longer needed. Method implementations are now in .cpp files, so the more conventional mechanism for initialising static variables would work fine.


Here is a sample of the pattern that we are using:

private:
    static std::shared_ptr<Reporter>& defaultReporter();

public:
    static std::shared_ptr<Reporter> getDefaultReporter();

    static void setDefaultReporter(const std::shared_ptr<Reporter>& reporter);

(See snippet source)

namespace ApprovalTests
{
    std::shared_ptr<Reporter>& DefaultReporterFactory::defaultReporter()
    {
        static std::shared_ptr<Reporter> reporter = std::make_shared<DiffReporter>();
        return reporter;
    }

    std::shared_ptr<Reporter> DefaultReporterFactory::getDefaultReporter()
    {
        return defaultReporter();
    }

    void
    DefaultReporterFactory::setDefaultReporter(const std::shared_ptr<Reporter>& reporter)
    {
        defaultReporter() = reporter;
    }
}

(See snippet source)

Note the use of the reference (&) on the return type of the private method, and the addition of a getter and setter method.