Declaring a string of fixed size

In C we do

char buffer[100];

Is there a way to declare a fixed size std::string?

6

6 Answers

You can use the string::reserve method like this

 std::string s; s.reserve(100);

But this isn't fixed size, because you can add more chars to the string with string::push_back for example.

In c++17, there will be std::string_view which offers the same (immutable) interface as std::string.

In the meantime, you can wrap a char array and add whatever services to it you choose, eg:

template<std::size_t N>
struct immutable_string
{ using ref = const char (&)[N+1]; constexpr immutable_string(ref s) : s(s) {} constexpr auto begin() const { return (const char*)s; } constexpr auto end() const { return begin() + size(); } constexpr std::size_t size() const { return N; } constexpr ref c_str() const { return s; } ref s; friend std::ostream& operator<<(std::ostream& os, immutable_string s) { return os.write(s.c_str(), s.size()); }
};
template<std::size_t NL, std::size_t NR>
std::string operator+(immutable_string<NL> l, immutable_string<NR> r)
{ std::string result; result.reserve(l.size() + r.size()); result.assign(l.begin(), l.end()); result.insert(result.end(), r.begin(), r.end()); return result;
}
template<std::size_t N>
auto make_immutable_string(const char (&s) [N])
{ return immutable_string<N-1>(s);
}
int main()
{ auto x = make_immutable_string("hello, world"); std::cout << x << std::endl; auto a = make_immutable_string("foo"); auto b = make_immutable_string("bar"); auto c = a + b; std::cout << c << std::endl;
}

As of Boost 1.66: A non-allocating string that emulates the interface of std::basic_string.

I don't know what you want to do, but with an std::array<char, 100> buffer; you should do fine.

You can then get a string like this:

std::string str(std::begin(buffer),std::end(buffer);

check this . you can replace char buffer[n]; with fss::fixed_size_string<n> buffer;

You could use std::array, which is the C++ method of doing exactly what you did in C.

std::array<char, 100> buffer;

If you're worried about stack overflow due to large buffer sizes (like, for example, if that 100 is a stand-in for 1'000'000) you could dynamically allocate it instead.

std::unique_ptr<std::array<char, 100>> buffer = std::make_unique<std::array<char, 100>>();

Since your interface takes a char * as its operand, and this object allows you to query for its size at runtime, this ought to suffice.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like