-2

Digging through MSDN, I ran into just another curious line:

// This function returns the constant string "fourth".
const string fourth() { return string("fourth"); }

The full example is buried here: https://msdn.microsoft.com/en-us/library/dd293668.aspx Refined to bare minimum, it looks like this:

#include <iostream>

const int f() { return 0; }

int main() {
    std::cout << f() << std::endl;

    return 0;
}

A few other tests with different return types demonstrated that both Visual Studio and g++ compile lines like this without a warning, yet const qualifier seems to have no effect on what I can do with the result. Can anyone provide an example of where it matters?

sigil
  • 755
  • 5
  • 11
  • Possible duplicate of [Should I return const objects?](http://stackoverflow.com/questions/12051012/should-i-return-const-objects) – Sergey Sep 27 '16 at 03:59

2 Answers2

2

you can not modify the returned object

example:

#include <string>
using namespace std;

const string foo(){return "123";}
string bar(){return "123";}

int main(){
    //foo().append("123"); //fail
    bar().append("123"); //fine
}

This is almost the same as const variable

#include <string>
using namespace std;

const string foo = "123";
string bar = "123";

int main(){
    //foo.append("123"); //fail
    bar.append("123"); //fine
}
apple apple
  • 5,557
  • 1
  • 12
  • 31
1

It is part of the return type. The functions return const string and const int.

In the case of const int, this indeed makes no difference compared to int, because the only thing you can do with an int return value is to copy the value somewhere (in fact, the standard explicitly says that const has no effect here).

In the case of const string, it does make a difference, because a return value of class type can have member functions called on it:

fourth().erase(1);

will fail to compile in the case that fourth() returns a const string, because erase() is not a const method (it tries to modify the string it is called on).

Personally, I never make value-returning functions return a const value, as it unnecessarily constrains the caller (although some people feel that it is useful to prevent writing things like string s = fourth().erase(1);).

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
M.M
  • 130,300
  • 18
  • 171
  • 314