如何实现同时支持堆栈和堆分配的 class

how to implement a class that supports both stack and heap allocations

强制 std::vector 使用基于堆栈的缓冲区的最直接方法是什么?我的猜测是使用 std::pmr::vector.

我想编写一个 class 的方式,既可以使用法线向量(使用动态分配),也可以使用自定义缓冲区。

这是一个示例:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cstddef>
#include <memory_resource>

// how should I implement this class? Using a template? How?
struct Foo
{
    explicit Foo( const std::size_t count = 1000, const char fillChar = ' ' )
    : vec( count, fillChar )
    {
    }

    std::pmr::vector<char> vec; // I need both normal and pmr vector
                                // (depending on what the client chooses to use)
};


int main( )
{
    std::array<std::byte, 10'000> buffer;
    std::pmr::monotonic_buffer_resource rsrc { buffer.data( ), 10'000 };
    std::pmr::vector<char> vec( 6000, '*', &rsrc ); // this free vector is a sample that
                                                    // shows how I may want to allocate
                                                    // a buffer for the vector member of Foo
    // print the content for demonstration
    std::copy_n( std::begin( vec ), 5, std::ostream_iterator<char>( std::cout, " " ) );
    std::cout << '\n';


    // how should I achieve the above or something similar for this object
    Foo foo { 2000, '!' };
}

我还想提一下,目标是简单,所以我很高兴看到一个相当简单的方法。但欢迎任何建议。

一种方法是模仿 vector 和别名模板 pmr::vector:

使用的设置
namespace foo {
  template <class Allocator = std::allocator<char>>
  struct Foo {
      using size_type = typename std::vector<char, Allocator>::size_type;

      constexpr Foo(size_type count, const char value,
                    const Allocator& alloc = Allocator())
          : vec(count, value, alloc) {}

      std::vector<char, Allocator> vec;
  };

  namespace pmr {
    using Foo = foo::Foo<std::pmr::polymorphic_allocator<char>>;
  }
}  // namespace foo

使用 foo::Foofoo::pmr::Foo:

int main() {
    foo::Foo x(1000, '^');

    std::array<std::byte, 10'000> buffer;
    std::pmr::monotonic_buffer_resource rsrc{buffer.data(), buffer.size()};   
    foo::pmr::Foo y(2000, '$', &rsrc);
}

Demo