3

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++?

UghSegment
  • 837
  • 1
  • 9
  • 12

2 Answers2

1

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.

1

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.

london-deveoper
  • 533
  • 3
  • 8