1

I have the following 2 functions:

void B::set(A * ptr){ this->a = ptr; this->info = get_some_info_from_a(*ptr); } T get_some_info_from_a(A& ref){ return ref.info; } 

As you see, I have A * ptr as a pointer in set(...), but I would need a reference to call get_some_info_from_a(...). So I dereference ptr and give it as an argument.

Is that correct? Is it efficient given A has some resources which must be copied by a copy/move constructor? I ask the question because it really seems that this line introduces some mysterious bugs.

4
  • 2
    Nope, it's fine. nothing will be copied. Commented Jul 9, 2014 at 14:50
  • 1
    get_some_info_from_a never accesses the ref argument, but returns a global variable named info. Is that what it's supposed to do? Commented Jul 9, 2014 at 14:51
  • @Frxstrem I think the real code would work out info from ref. Commented Jul 9, 2014 at 14:52
  • Oh, that's embarassing. Of course info would be taken from ref. It's corrected now. Commented Jul 9, 2014 at 14:57

2 Answers 2

6

It's correct and efficient. Performing indirection with *ptr just gets you the value that ptr points to and then you are passing that by reference to get_some_info_from_a. That value is never copied.

Sign up to request clarification or add additional context in comments.

Comments

1

This is fine and will not invoke any copy/move ctor as you are calling by reference. However, a const or two (if a member function) in the function signature wouldn't go a miss:

T get_some_info_from_a(const A& ref) const { 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.