Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discourage use of References #5

Open
mkristien opened this issue Oct 25, 2019 · 4 comments
Open

Discourage use of References #5

mkristien opened this issue Oct 25, 2019 · 4 comments

Comments

@mkristien
Copy link
Contributor

void foo(int& val); or
void foo(int* val); ?

I do not like references because they look like passing values around but they behave like pointers. This can lead to programmers' errors.

@neilweidinger
Copy link
Member

Can you specify what kind of errors? I'm of the opinion that we should actually be encouraging usage of references, especially const myDataType& variable_name, since this avoids accidentally changing the state of the value passed in and is closer to idiomatic C++11 than raw pointers.

@mkristien
Copy link
Contributor Author

The error happens if people assume value semantics while the code has pointer semantics.
Last year, original embrakes code had this:
Data stateMachineData = Data::getInstance();
This created a copy of the shared data structure, thus updates to it were done to the copy and not to the one and only. This could have been prevented if Data::getInstance() returned Data* instead of Data&.

@brano2
Copy link
Member

brano2 commented Oct 27, 2019

@mkristien in that example, the real problem is that the singleton pattern for the Data class was not implemented properly (I suppose the constructor that converts a reference to a value was not deleted). It does not work any more afaik even though Data::getInstance() still returns a reference.

@brano2
Copy link
Member

brano2 commented Oct 27, 2019

I don't think references are confusing as they are the closest thing C++ has to languages like Java or Python which only have one way of passing things around. Hence most programmers should be more skilled at working with references than working with pointers/values. If there is evidence that people were actually messing up with references much more often than with values and pointers, I'll change my opinion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants