'C++ container without C++ standard lib
In the context of embedded software I want to make a std::vector-like container.
Vector has both size and capacity, which means vector has allocated capacity*sizeof(T) bytes, but only size entries are constructed.
An example
vector<string> v;
v.reserve(100)
v.resize(10)
v[9] gives a valid string , but v[10] gives a valid allocated memory portion of uninitialized data, so any string method will have an undefined behaviour, like v[10]= string(), if string& operator(const string& rhs) tries to destroy *this.
How can I build an object in a given memory address just using C++ compiler without including <new> or any other C++ standard include files?
UPDATE Can I write a custom implementation of placement new operator and make final executable independant from libstdc++.so? I don't want static linking against libstdc++.a either.
Solution 1:[1]
How can I build an object in a given memory address just using C++ compiler without including or any other C++ standard include files?
You have to read your compiler documentation and/or source code and related libraries and find out what is needed for that particular compiler with particular options used by you to allow this particular compiler with this particular configuration to work with placement new. I.e. if you can't use portability features like header files, you have to provide the compiler with your own non-portable replacement of header files.
For example, the following should be fine for gcc x86_64:
inline void* operator new(unsigned long, void* __p) { return __p; }
inline void operator delete(void*, void*) { }
struct A {};
int main() {
alignas(A) char buf[sizeof(A)];
struct A *a = new (buf) A;
a->~A();
::operator delete(buf, a);
}
make final executable independant from libstdc++.so?
In the same way, compiling against LLVM libc++ makes the executable independent of GNU libstdc++. Provide your own implementation of needed functions in libstdc++ and link with them.
Placement new are inline empty functions on gcc. They use no symbols from the shared library.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KamilCuk |
