3

i have vector of pointers: std::vector<Customer*> customersList Now i want to get one of the elements and make my operations on him. i'm not sure that i know how, my guess was:

Customer* source = restaurant.getCustomer(cust); 

the problem is that i don't know if in c++ it will create new object or i will just get a reference to him. There is my getter method:

Customer* Table::getCustomer(int id) { for (int i = 0; i < customersList.size(); ++i) { if (customersList[i]->getId() == id) return customersList[i]; } return nullptr; } 

Thank you

7
  • 6
    It copies the pointer, but not the pointed object. Commented Nov 12, 2018 at 9:43
  • Great so i'm not make any copy of the object himself, am i right? Commented Nov 12, 2018 at 9:44
  • 1
    Yup, it'll point to the original object. Commented Nov 12, 2018 at 9:45
  • 1
    If your source is a pointer (or vector of pointers) and you're returning a pointer, there will be no new object created unless you specifically go out of your way to create one. For example, calling a clone() function that deliberately allocates a new object and returns its address. The default behaviour is that the object is not deep copied (i.e. a new object is not created). Commented Nov 12, 2018 at 9:46
  • 1
    Pointers are objects too, that's why you can have a std::vector of them. Commented Nov 12, 2018 at 10:52

1 Answer 1

5

The member function will return a copy of the pointer, i.e. the Customer object itself is not copied, only the reference to it. Modifying the returned Customer* will result in modifications of the pointee (the underlying object).

Note that you also want to use the <algorithm> header, specifically std::find_if.

const auto customer = std::find_if(customerList.begin(), customerList.end(), [id](const Customer* c){ return c->getId() == id; }); return customer == customerList.cend() ? nullptr : *customer; 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. what if i want to make changes on that object, const not make it forbidden?
The const auto customer forbids any changes to the iterator named customer. The object it points to can be modified.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.