What does the pointer returned by String::getPtr() point to? Is it pointing to a member of String? If so, in your first example, it's pointing at a member of an object that has been destroyed, in the second example it's pointing at a member of the object that still exists (under the name "temp").
Undefined behavior will not produce the same results on every kind of machine. That is why we use the term "undefined". Is getPtr coded correctly? How would we know since we can't see its definition?
If I understand things correctly, you are calling a function on a temporary object that is constructed but not assigned to a variable in the first example. I'm assuming you compiled for each machine so look at the assembly and see if the temp is being destroyed at a different time? I would never trust code like example 1 without first having a detailed understanding of the C++ std. When exactly will the system return that memory to stack and destroy the object along with the underlying string? Example 1 just looks like a bad idea. Perhaps you should consider making a static template function that uses stringstream to do the conversion rather than using a class that has to be constructed.