0

I am working with a library that I can't change and have been set a task to complete with the library.

Although I have done the task and it works, I don't really understand why it works and whether I should do it.

I have a function in a cpp file

void Foo (const String &someName) { OtherFoo (&someName) } 

where Foo passes a reference to a const string and OtherFoo requires a pointer to const string to be passed to it.

So basically ref is a const string& and needs to be passed into OtherFoo as a const pointer (const & to const *)

Is what I've done OK? (passing the address of the ref to the function that requires a pointer to const string)

Is there any negatives with how I have passed the argument? Could someone explain exactly why it works?

Many thanks

3
  • (As for "vocabulary", const foo * is a pointer-to-const and not a const pointer (that would be foo * const), const foo & is a reference-to-const. Makes things less ambiguous.) Commented Mar 30, 2015 at 10:12
  • Thanks - have reworded for const correctness. Please edit if you see any more. Commented Mar 30, 2015 at 10:17
  • Remember that Foo can be called with a temporary object and the lifetime of the temporary will be the call Foo. If OtherFoo stores the pointer for later use somewhere and that use happens after Foo is done, the pointer will point to a a dead object. Commented Mar 30, 2015 at 10:40

1 Answer 1

2

Yes, this is a correct way of doing it. Indeed, taking the address of a reference yields in fact the address of the referent.

So in this case, the type of the expression &someName is actually const String *.

Be careful not to mix constness of the pointer and constness of the pointee though. In this case, when you say "const pointer", it's actually pointer to const which is not the same thing.

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

1 Comment

Thanks - I have edited for const correctness. if you see any other ambiguous statements of mine please feel free to edit them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.