I would like to write me own class String which will have interface similar to std::string. String class shall not use dynamic memory allocation.
I need to have a c-tor:
String(char* ptrToFirstCharInTab, char* ptrToLastElementInTab);
And there should be tab which contains different (not know) number of element, so I do not know size while compiling.
In my opinion it's impossible, because if we do not know size of our array before compilation we can not create it without dynamic allocation - of course creating buffer for 500 char and then String class can be only 500 it' not my expections.
Do you have any idea? Maybe is any way to create buffor wchich I will shrink to fit? Thanks for help!
You asked:
Is it possible to create class String without using heap in C++?
In fact, yes, it possible to dynamicly allocate memory on the stack by using _alloca
or similiar platform dependent function. See this other answer for more details:
C++ How to allocate memory dynamically on stack?
I would recommend against it and be absolutely sure that was the best alternative before commencing.
Update:
I created an example with inlined constructer for demonstration purpose using gcc
:
Compiler explorer Link: https://godbolt.org/z/M1F5VD
Full code:
#include <alloca.h>
struct String {
__attribute__((always_inline)) inline String(size_t size) {
bytes= static_cast<char*>(alloca( size ));// alloca() memory gets allocated here
}
char* bytes;
};
int workWithString( )
{
//std::string teststr("test");
String mystrclass(1000);
mystrclass.bytes[0] = 'a';
mystrclass.bytes[1] = 0;
return 0;
} // alloca() memory only gets freed here
int main() {
return workWithString();
}