Pointed Object Link

Dereferencing pointers can make code very difficult to read. Usually I make a link to a pointed object and work with the link. Example:

shared_ptr<std::vector<int> > sp = get_sp_to_vector();
std::vector<int>& vec = *sp;
...
vec.push_back(5);

Interestingly, this is a good practice. Does he have a flaw?

Update: To complete this example, I would define it get_sp_to_vector()as follows:

shared_ptr<std::vector<int> >  get_sp_to_vector()
{
    // create a vector and send back a shared pointer pointing at it
    shared_ptr<std::vector<int> >  sp(new std::vector<int>);
    sp->push_back(1);  sp->push_back(3);
    return sp;
}
+3
source share
5 answers

The use of local links is a common occurrence, especially inside the body of the loop, but there is one requirement: do this only when the link will obviously live as long as the target.

This is usually not difficult to guarantee, but here are some bad examples:

shared_ptr<X> p = get_p();
X& r = *p;
p.reset(); // might result in destroying r
use(r); // oops

// or:
shared_ptr<X> p = get_p();
X& r = *p;
p = get_some_other_p(); // might result in destroying r
use(r); // oops
+2
source

. C/++ b/c , C/++ de-reference, . , ( ), . , gnarly b/c, , , , - , , , , , , . :

shared_ptr<std::vector<int> > sp = get_sp_to_vector();
std::vector<int>& vec = *sp;
...ugly stuff...
vec.push_back(5);

:

void func(std::vector<int> &vec)
{
     ... previously ugly stuff...
     vec.push_back(5);
}

shared_ptr<std::vector<int> > sp = get_sp_to_vector();
func(*sp);

EDIT:
, , , , , . , * p p- > x, , p.x. , C/++.

, . , .

+2

, , ( - . ). push_back(), , .

, , , , ( , , ..).

+2

, . - , . , (I.e., non-nil ), , .

+1

, , :

shared_ptr<std::vector<int> > sp = get_sp_to_vector();
...
sp->push_back(5);

"very hard to read." It is also shorter than your code. Therefore, although I do not think that there are many mistakes in defining and using a local link, I also do not think that you should make a rule to always do this.

Perhaps if your pointer code is very difficult to read, this is because you are missing a trick that will simplify it. Perhaps if you ask another question with an example of a bad pointer code that you currently corrected with a link, SOers will find alternative fixes.

+1
source

Source: https://habr.com/ru/post/1729169/


All Articles