std::basic_string
에 사용자 지정 할당자를 전달할 수 있습니다.이 할당 자의 최대 크기는 원하는대로 지정합니다. 이것은 충분해야합니다. 이 같은 아마 뭔가 :
template <class T>
class my_allocator {
public:
typedef T value_type;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
pointer address(reference r) const { return &r; }
const_pointer address(const_reference r) const { return &r; }
my_allocator() throw() {}
template <class U>
my_allocator(const my_allocator<U>&) throw() {}
~my_allocator() throw() {}
pointer allocate(size_type n, void * = 0) {
// fail if we try to allocate too much
if((n * sizeof(T))> max_size()) { throw std::bad_alloc(); }
return static_cast<T *>(::operator new(n * sizeof(T)));
}
void deallocate(pointer p, size_type) {
return ::operator delete(p);
}
void construct(pointer p, const T& val) { new(p) T(val); }
void destroy(pointer p) { p->~T(); }
// max out at about 64k
size_type max_size() const throw() { return 0xffff; }
template <class U>
struct rebind { typedef my_allocator<U> other; };
template <class U>
my_allocator& operator=(const my_allocator<U> &rhs) {
(void)rhs;
return *this;
}
};
그런 다음 당신은 아마이 작업을 수행 할 수 있습니다
typedef std::basic_string<char, std::char_traits<char>, my_allocator<char> > limited_string;
편집 : 난 그냥 예상대로이 작동하는지 확인하는 테스트를 수행했습니다. 다음 코드는이를 테스트합니다.
int main() {
limited_string s;
s = "AAAA";
s += s;
s += s;
s += s;
s += s;
s += s;
s += s;
s += s; // 512 chars...
s += s;
s += s;
s += s;
s += s;
s += s;
s += s; // 32768 chars...
s += s; // this will throw std::bad_alloc
std::cout << s.max_size() << std::endl;
std::cout << s.size() << std::endl;
}
마지막 s += s
가 std::bad_alloc
예외를 맨 위에 넣고 일으킬 것이다, (내 한계는 64K의 단지 짧기 때문에). 불행히도 gcc의 std::basic_string::max_size()
구현은 사용하는 할당 자의 결과를 기반으로하지 않으므로 더 많은 할당을 할 수 있다고 주장합니다. (이것이 버그인지 아닌지는 잘 모르겠습니다 ...).
하지만이 방법을 사용하면 간단한 방법으로 문자열의 크기를 엄격하게 제한 할 수 있습니다. 템플릿 매개 변수의 최대 크기를 만들 수도 있으므로 할당 자에 대한 코드를 한 번만 작성하면됩니다.
int 템플릿 매개 변수을 추가했고 max_size()가 N을 반환했습니다. 그런 다음 그는 typedef std :: basic_string , my_allocator > my256string을 수행 할 수 있습니다. –
jmucchiello
'size_type'을 템플릿 인수로 사용하는 것이 유익 할 것이라고 생각합니다. 그러면 사용자는 주어진 문자열 인스턴스에 가장 적합한'size_type'을 자유롭게 선택할 수 있습니다. 그런 다음 부분 템플릿 전문화는이 유형을 'basic_string'으로 멋지게 만드는 데 도움이됩니다. –