0
\$\begingroup\$

In my project, I'm trying to use the std::pmr allocator and monotonic_buffer_resource. I'm using vector in various classes, and I need to use the same resource in all of them. I created a separate free function that returns the resource pointer and used it while declaring the vectors. Here is the code

#include <memory_resource>
#include <vector>
#include <array>

std::pmr::monotonic_buffer_resource *getMemoryResource()
{
    static std::array<std::byte, 100000> buffer;
    static std::pmr::monotonic_buffer_resource resource{buffer.data(), buffer.size()};
    return &resource;
}
struct JsonData
{
    std::pmr::vector<int> data{getMemoryResource()};
};
struct XMLData
{
    std::pmr::vector<char> data{getMemoryResource()};
};

Is there anything I can do to improve the code, especially getMemoryResource function?

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

Since there is so little code to review I only have one observation to make:

Magic Numbers

There is a Magic Numbers in the getMemoryResource() function (100000), it might be better to create a symbolic constant for it to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.

Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.

\$\endgroup\$
3
  • \$\begingroup\$ Thanks for the review. The code is small because I removed the unnecessary code which is like parsing the Json and XML files.My main focus is how can I use the getMemoryResource() function.I mean whether I can make it constexpr or some other improvements.Will remove the magic number and make it configurable by the user. \$\endgroup\$
    – goodman
    Commented Dec 31, 2022 at 15:27
  • 1
    \$\begingroup\$ @goodman On the Code Review community there is no unnecessary code. We can provide better reviews with more code. How to questions are off-topic on the Code Review community. \$\endgroup\$
    – pacmaninbw
    Commented Dec 31, 2022 at 16:37
  • \$\begingroup\$ Actually I have to disagree. If the number was used in multiple places, configured (by the build-process), or its effect wasn't obvious without naming it, creating a constant for it would make sense. As-is, it would just complicate things. \$\endgroup\$ Commented Jan 1, 2023 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.