Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting pointers to (const) references

When using a function from an external library, is it safe to 'arbitrarily' dereference pointers into const references?

SomeType const& obj = *LIB_CreateSomething();

Is this universally safe/smart to do?
More importantly, is there really a good reason to do this over using a const pointer other than raw pointers being "frowned upon" in C++?

like image 937
UghSegment Avatar asked Feb 19 '26 19:02

UghSegment


2 Answers

It's certainly not universally a good idea, or generally a good idea at all. If a function returns a pointer, particularly if it called something like CreateX, there is a good chance that you need to manage the lifetime of the the thing the pointer points to,. You can't do this via a reference, but you can via a smart pointer.

In general, you do not want to be creating reference variables. References in C++ are intended to be used mainly as function parameters and return values.

What you really want to do is something like the following (see code). Const objects are initialized at creation. Some compilers understand what you are trying to do and do not complain about this form of assignment.


    SomeType const& obj(*LIB_CreateSomething());

Typically in C++ you wouldn't do that though.

One reason is that 'raw' (naked) pointers are only really frowned upon when you are the owner. If it doesn't belong to you then stylistically there is nothing wrong with using a pointer.

Another is that the pointer might be null and casting a NULL directly to a reference will render the reference unusable.

As mentioned in another comment you might in fact be the owner and in that case you would be expected to manage the memory. You cannot do that with a reference.

like image 35
london-deveoper Avatar answered Feb 21 '26 07:02

london-deveoper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!