Issue with dereferencing operator and functions

I have an A () function that returns a pointer to an object. In function B (), I am trying to change the member of this object as follows:

void B()
{
    ObjType o = *getObj();
    o.set("abc");
}

The o object is stored in an array, and when I print the value of the member, nothing seems to have happened and the element still has the old value;

The solution is pretty simple:

void B()
{
    ObjType * o = getObj();
    o->set("abc");
}

It works. But for me this is exactly the same as the first sample. Can anyone explain this?

+3
source share
4 answers

Most likely, the following copy of the object:

ObjType o = *getObj();

That is why nothing happens. If you do not want to use a pointer, as shown in the second snippet, you can use a link, for example:

ObjType& o = *getObj();
o.set("abc");
+9
source

. . .

+4

Of course, this is not the same. The first copies the object pointed to by the returned pointer to a local object in your stack, and then modifies the copy.

The second saves a pointer to the returned object and modifies it with a pointer, thereby changing the original.

A third solution would be to use links.

+3
source

These two options are completely different:

   ObjType o = *getObj();

creates a new copy of an object named o

   ObjType * o = getObj();

creates an apointer called o that points to an existing copy - a new created object

+2
source

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


All Articles