Here's my guess, as we're currently missing some relevant information.
Does your get_string()
method maybe return a (possibly const) reference to a my_second_class
instance ?
If that is the case, then the first attempt fails because mySecCls
is a local object that gets destroyed when the function returns. After that destruction happens, MyNSString
points to some invalid memory location on the stack. The second attempt works because no such local (i.e. temporary, from the point of view of your class) object gets created, and the pointer passed points to the contents of the more durable myCls
object.
(I also assume that my_string()
returns a const std::string&
and not a string
, or you'd get the same kind of issue with the resulting temporary variable).
If you want to make something that works like attempt #2, but looks a bit more like attempt #1, you can try:
- (void)setInfo {
const my_second_class& mySecCls = myCls->get_string();
MyNSString = @(mySecCls.my_string().c_str());
}
However, this is pretty much equivalent to attempt #1.