I understand for pointers and objects making them const while returning returns a locked copy of that object so like for objects only const functions can be called on it.
I was wondering is there any sense in returning const int from a function. Since int is just a primitive type I don't see any difference between: const int& myFunction();
and int& myFunction();
.
Is there any small difference between the two that I am missing here or are they EXACTLY the same and therefore writing const before int& return type is just stupid?
Edit:
#include <vector>
const int& getConstInt() { return 1; }
int& getInt() { return 1; }
std::vector<int> getSimpleVector() { return std::vector<int>(); }
const std::vector<int> getConstVector() { return std::vector<int>(); }
int main() {
int constInt = getConstInt();
int simpleInt = getInt();
constInt = 2; // does not matter that the return type was const
simpleInt = 2;
std::vector changedAfterReturn = getConstVector().push_back(3); //locked, gives error
changedAfterReturn = getSimpleVector().push_back(3); //not locked... works fine.
getInt() = 2; // This never made any sense in the first place since int is a primitive value.
getConstInt() = 2; // Neither does this. So whats the use in declaring const.
return 0;
}
Updated the question to ask for difference between return value of int& vs const int& instead of return by values.