title: Why is c++ prematurely destroying my string variable?
body: <p>This error is one of the most mysterious I've gotten in probably years. I've been trying things back and forth for hours now and can't understand it.</p>
  
  <p>In the code below, I am trying to dynamically decide which derived class to instantiate. I use the function parameter <code>particle_type</code> in order to determine that.</p>
  
  <p>But since </p>
  
  <pre><code>Particle p;
  </code></pre>
  
  <p>is not allowed, since you have to initialize references, I am trying to do it with a pointer as below.</p>
  
  <pre><code>Particle* p;
  if (particle_type == "Featherr") { //This is never called because of the extra "r" I put, so ignore this block
          p = &amp;FeatherParticle(particle_name, position, rotation, velocity, gravityEffect, lifeLength, scale);
  }
  else {
      p = &amp;Particle(particle_name, position, rotation, velocity, gravityEffect, lifeLength, scale);
  }
  
  Particle particle1 = *p;
  Particle particle2 = Particle(particle_name, position, rotation, velocity, gravityEffect, lifeLength, scale);
  
  particles.push_back(particle1);
  particles.push_back(particle2);
  </code></pre>
  
  <p>Now the particle2 is just me debugging, but it highlights this bug* very well. I put a breakpoint at <code>particles.push_back(particle1);</code> and found that the particle object stored by <code>particle1</code> was broken:</p>
  
  <p><a href="https://i.stack.imgur.com/yJCzz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yJCzz.png" alt="enter image description here"></a></p>
  
  <p>I do not understand why the string is set to "" here. I can only guess it has to do with the scoping, because if I set the string outside the else statement, it works. Which makes my jaw drop at how stupid this functionality is *which is why I think it may be a bug or near-bug functionality.</p>