Note that there are some explanatory texts on larger screens.

plurals
  1. PORealloc()/Resize an object in C++ for a string implementation
    text
    copied!<p><strong>When they are represented in memory, are C++ objects the same as C structs?</strong></p> <p>For example, with C, I could do something like this:</p> <pre><code>struct myObj { int myInt; char myVarChar; }; int main() { myObj * testObj = (myObj *) malloc(sizeof(int)+5); testObj-&gt;myInt = 3; strcpy((char*)&amp;testObj-&gt;myVarChar, "test"); printf("String: %s", (char *) &amp;testObj-&gt;myVarChar); } </code></pre> <p>I don't think C++ allows overloading the <code>+</code> operator for the built-in <code>char *</code> type.</p> <p>So i'd like to create my own lightweight string class which has no extra overhead that <code>std::string</code> has. I think <code>std::string</code> is represented contiguously:</p> <pre><code>(int)length, (char[])data </code></pre> <p>I want exactly the same functionality but without prefixing the length (saving 8 bytes overhead).</p> <p>Here is the code i'm using to test, but it results in a segfault</p> <pre><code>#include &lt;iostream&gt; using namespace std; class pString { public: char c; pString * pString::operator=(const char *); }; pString * pString::operator=(const char * buff) { cout &lt;&lt; "Address of this: " &lt;&lt; (uint32_t) this &lt;&lt; endl; cout &lt;&lt; "Address of this-&gt;c: " &lt;&lt; (uint32_t) &amp;this-&gt;c &lt;&lt; endl; realloc(this, strlen(buff)+1); memcpy(this, buff, strlen(buff)); *(this+strlen(buff)) = '\0'; return this; }; struct myObj { int myInt; char myVarChar; }; int main() { pString * myString = (pString *) malloc(sizeof(pString)); *myString = "testing"; cout &lt;&lt; "'" &lt;&lt; (char *) myString &lt;&lt; "'"; } </code></pre> <hr> <p>Edit: nobody really understands what i want to do. Yes i know i can have a pointer to the string in the class but thats 8 bytes more expensive than a plain cstring, i wanted exactly the same internal representation. Thanks for trying though</p> <hr> <p>Edit: The end result of what i wanted to achieve was being able to use the + operator with NO extra memory usage compared to using strcat etc </p> <pre><code>const char * operator+(const char * first, const char * second); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload