Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Beyond the compiler error, which has already been answered, your code has some other problems. (At least, assuming the code you posted is near or exactly what you're actually using in your project.)</p> <p>Even if you change <code>_widget_base</code> to be a const pointer, this line of code is a problem:</p> <pre><code>_widget_base = str.substr(pos1, pos2-pos1).c_str(); </code></pre> <p><code>substr</code> returns a temporary string object. The result of <code>c_str()</code> is still owned by that temporary string. And the way that line is written, the temporary string object will be destroyed after the line is executed. Thus the problem is that <code>_widget_base</code> will be left pointing to an area of memory that has been deleted and which may be reused at any time.</p> <p>You may also have similar problems with <code>_name</code> depending on what you pass into Widget's constructor.</p> <p>So you could do one of three things with <code>_widget_base</code> and <code>_name</code></p> <p>1) Dynamically allocate memory yourself so that it is not managed by any other objects.</p> <pre><code>std::string temp = str.substr(pos1, pos2-pos1); _widget_base = new char[temp.length()+1]; strcpy(_widget_base, temp.c_str()); </code></pre> <p>Of course, you would also need to manage the deletion of this memory in your Widget's destructor. And also possibly reallocation if this value could be changed while a Widget exists.</p> <p>2) Make those member variables character arrays instead of pointers. That way the memory is a permanent part of Widget can doesn't need to be managed. Of course, you'd also have to determine how big is big enough for the arrays.</p> <pre><code>char _name[a big enough value]; char _widget_base[a big enough value]; </code></pre> <p>and then:</p> <pre><code>std::string temp = str.substr(pos1, pos2-pos1); strcpy(_widget_base, temp.c_str()); </code></pre> <p>3) Make those member variables string objects.</p> <pre><code>std::string _name; std::string _widget_base; </code></pre> <p>and then:</p> <pre><code>_widget_base = str.substr(pos1, pos2-pos1); </code></pre> <p>This way is the most preferable since it is the most robust and least prone to errors. You have no memory to directly manage and no worry about values that are too large to hold.</p>
 

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