Problem with references


C

carl

In a function 'update()' I read and update a std::vector<MyObj> located in
another object 'Test'.

Now I would like these changes to be visible after 'update()' returns (both
for the container and the elements inside).

The function I use to read the std::vector<MyObj> therefore returns a
reference to the container:

std::vector<MyObj> & Test::getContainer()
{
return m_container;
}


Here is the implementation of 'update()'

void update(){

std::vector<MyObj> container = test.getContainer();
int size = container.size();
for (int i=0; i<size; i++) {

// Changes to objects in the container should be visible outside this
function.
MyObj & mo = container;
mo.setId(i);

}

// Below should be unnecessary
test->setContainer(container);


}

But the changes are not visible after 'update()' returns unless I add the
call:

test->setContainer(container);

after the above loop. But is the point of using references not that this
kind of explicit updating is unncessary?
 
Ad

Advertisements

J

Jeff Flinn

Daniel said:
carl said:
In a function 'update()' I read and update a std::vector<MyObj> located in
another object 'Test'.

Now I would like these changes to be visible after 'update()' returns (both
for the container and the elements inside).

The function I use to read the std::vector<MyObj> therefore returns a
reference to the container:

std::vector<MyObj> & Test::getContainer()
{
return m_container;
}

Here is the implementation of 'update()'

void update(){

std::vector<MyObj> container = test.getContainer();
int size = container.size();
for (int i=0; i<size; i++) {

// Changes to objects in the container should be visible outside this
function.
MyObj & mo = container;
mo.setId(i);
}

// Below should be unnecessary
test->setContainer(container);
}

But the changes are not visible after 'update()' returns unless I add the
call:

test->setContainer(container);

after the above loop. But is the point of using references not that this
kind of explicit updating is unncessary?


'container' isn't a reference, only the return value of getContainer()
is. Oddly, you made 'mo' a reference so you seem to understand the
principle.

Frankly, if you are going to make getContainer() return a reference
anyway, why not just make 'm_container' public?


Or better yet make it Test::update, and have it the behavior encapsulated.

Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top