Hi all, a got a problem that i just realized several days ago about my increased sensitivity to using local pointers and references, well previously i didn't have this issue though i still knew what happens to local &/* but it probably got aggravated after reading an article by Stroustrup.
I'll need some help understand what will happen in the following instances:
1.
std::vector<int> vect{1,2,3,4,5,6,7};
void funct(std::vector<int>& v)
{
auto& local_ref=v[3];///use local_ref
}
funct(vect);
///will the element vect[3] exist in a valid state after the call;
2.
class foo
{
///
}
foo* newInstance()
{
foo* local_ptr=new foo(Args..);
return local_ptr;
}
auto ptr=newInstance();
///what will happen to the local_ptr pointer after the call
3.
map<std::string,object> mp_obj;
void process_ref( map<std::string,object>& mp_obj)
{
std::string key("object_one");
auto o_iter=mp_obj.find(key);///assuming key is found
///use result
}
///what will happen to object referred to by o_iter after the
/// the function exits
2. The variable local_ptr no longer exists in the current scope, but since you returned and assigned the value to "ptr", you now still have the handle on an instance of foo.
3. Not too familiar with iterators, but it should be the same as anything else, if you used o_iter to change your mp_obj, then the object referenced by mp_obj will still be changed after the function exits.
Well thanks @Ganado but does that mean destructors aren't called on */& after their scope exits? because if that's the case their content should be destroyed at scope exit and before any returned value is copied i believe .
Oh thanks mike but then why would Stroustrap emphasize so much about avoiding local &/* I know itsn't safe but i don't understand how or what causes them to be unsafe
Oh thanks mike but then why would Stroustrap emphasize so much about avoiding local &/* I know itsn't safe but i don't understand how or what causes them to be unsafe
I think you're misunderstanding. You want to avoid keeping a reference or pointer to an object local to an enclosed scope (such as that defined by a function) because those objects are destroyed when the enclosed scope ends (although the reference or pointer may not be.)
Also note that, if you do this with references it's not an error... but it's undefined behaviour at runtime since a reference isn't (usually) allocated with new (and if you allocate with new and return a reference to that object... you're a bad person! >:( ) and since the object is still local to the function (the reference doesn't extend the local's lifetime) it gets destroyed (and the function returns a reference to a destroyed item)
That is a correct snip. You shouldn't RETURN a reference, unless you have a reason to do so (eg some class member operators usually return references to themselves)