0

Problem

Basically I am just looking for a text replacement for a object which i have to access through a nested structure so I don't have this long lines.

Camera cam = clients_manager.network_controlled_simulations[simulation_index].simulation.agents[agent_index].cameras[camera_index];
cam.do_stuff();

However this creates a copy of the Camera object. Which in turn crashes my program further down the line. Which is not the behaviour I want. I don't want a copy i just want to avoid this long lines and have readable code.

Things i've tried

1.

One way which would work:

Camera *cam = &clients_manager.network_controlled_simulations[simulation_index].simulation.agents[agent_index].cameras[camera_index];
(*cam).do_stuff();

But then everytime i want to use a method or property I have to do (*cam).property and (*cam).method()

I'd prefer accessing it like:

cam.property

2.

So i thought I would do:

Camera cam;
*cam = &clients_manager.network_controlled_simulations[simulation_index].simulation.agents[agent_index].cameras[camera_index];

Which gives me the error:

No operator "*" matches these operands
Operand types are: * Camera

3.

Then Well let's try address operator & :

Camera cam;
&cam = &clients_manager.network_controlled_simulations[simulation_index].simulation.agents[agent_index].cameras[camera_index];

which gives me another error:

expression must be a modifiable lvalue

Question

Is there any way to achieve what I want or should I just settle with the solution i found ?

KoKlA
  • 898
  • 2
  • 11
  • 15
  • 2
    References are essential to write any non-trivial code, you should read about them. https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – 463035818_is_not_an_ai Sep 28 '22 at 10:49
  • 1
    Since your object's subscript operator already returns cameras by reference, what about using a reference instead ? `Camera & cam = ...;` – Fareanor Sep 28 '22 at 10:49
  • 1
    "But then everytime i want to use a method or property I have to do (*cam).property and (*cam).method()" No. `cam->property` or `cam->method()` is the canonical way to dereference and access a member – 463035818_is_not_an_ai Sep 28 '22 at 10:50
  • 1
    Use a reference `Camera& cam = clients_manager.network_controlled_simulations[simulation_index].simulation.agents[agent_index].cameras[camera_index];` – john Sep 28 '22 at 10:51
  • Thank you @StackDanny Fareanor and 463035818-is-not-a-number . Question can be closed . – KoKlA Sep 28 '22 at 10:51
  • @john thank you as well, that's the solution yes. I didn't knew about reference variable. I always thought they were just operators used in function signatures to indicate pass by reference or to access the adress of an existing object. Thx everyone I am gonna stop replying now. – KoKlA Sep 28 '22 at 10:54

0 Answers0