Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ functions accepting both pointers and references

I am writing a library in C++ and have some functions that work with modules. An example would look like this:

void connect(Module *a, Module *b);

The problem is, that it would be sometimes handy if the function accepted also references (some of the Modules may be allocated on the stack and some on the heap and all the &s and *s get boring and messy soon).

Now I have inlined function that takes references, turns them into pointers and calls the original function.

inline void connect(Module &a, Module &b){
    connect(&a, &b);
}

I don't like this solution much, because for a few more functions it makes a lot of code to write, read, compile, ...

Another thing that was thinking about is adding Module::operator Module *() that would hust return this.

What are your thoughts on this? Isn't there any potential for epic failure that I missed?

Thanks.

like image 261
cube Avatar asked Dec 20 '25 12:12

cube


1 Answers

Why not just call the function with

connect(&a, &b);

like in your inline function, whenever you have to call it with references? This makes it very clear that the function takes pointers, and that a and b are not pointers. You only have to type two more characters.

like image 142
Zifre Avatar answered Dec 23 '25 02:12

Zifre