#Question about pointers

19 messages · Page 1 of 1 (latest)

frank salmon
#

data = new int(*other.data);

i'm having trouble figuring out when i should use pointers like this, the first part being without de-reference operator

vs using de-reference operator (i'm aware you use this to access the value or modify it, i think?)

jagged moonBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

digital iron
#

For the first half of your post, *other.data can be rewritten as other->data. The -> dereferences a pointer to something before accessing that pointed-to thing's field.

For the second part, sounds fine overall. It's to get to the object referenced by a pointer, object meaning something in memory. Then you can do what's needed. Be cautious though when using owning raw pointers.

frank salmon
#

Sorry you're misunderstanding what i'm asking

data = new int(*other.data);

i understand i need to de-reference **other.data to assign the value to data on the left hand side. What i don't get, is what i don't use a de-reference operator on the left hand side

#

Will check back tomorrow, getting off computer

digital iron
#

I see. If data is a pointer, no need to dereference it here. new gives a pointer to the allocated object, thus data = new int(*other.data) is just setting the data pointer to point to the other's data.

(I assume the LHS name is for a field declared as int* data)

gaunt bolt
#
  • dynamic sized data
  • data that lives after it's scope ends
#

but for stuff like dynamic arrays you are better off with std::vector

shy zinc
#

You should never use pointers like this.

#

This is how to make you hate C++ for being impossible to manage.

#

As a rule of thumb, never use new and a lot of issues will go away.

gaunt bolt
#

it's good to know what it is, but I don't remember the last time I actually needed it

#

Like we have every simple data type in STL already

#

and even if I need a more complicated one, it'll be just the STL containers used in a specific way

#

like a bi-map is just two unordered maps

#

a 2d dynamic array is just one vector indexed by 2 numbers

#

etc.

#

for dynamic memory you have smart pointers that do the work for you