Why is a string passed as a constant string in a function parameter

I am a little confused by one example in my tutorial. When a string is created, it is created as a type string. However, when the same string is passed to the function, the parameters of the function have a constant, not a string.

Here is the piece of code:

int main()
{
string str;
cout << "blah blah..";
getline(cin, str);
if (is_pal(str))

.
.
.
}
bool is_pal(const string& s)
{
.
.
.
}

why the function parameter const string & s instead of just string & s? I turned the entire tutorial, but I can not find an explanation for this = / Thank you.

+4
source share
6 answers

, , std::string, const lvalue ++. ; . const lvalue lvalues ​​ rvalues ​​ - , , .

+6

const , , .

, , , const .

, , - , , . , const.

void foo_will_not_modify (const std::string &x); // const ref - won't modify
void bar_will_not_modify (std::string x);        // copy - won't modify
void baz_will_modify (std::string &x);           // reference - can modify
+2

Re

" const string& s string& s?

, , +, "rvalue".

, , ++, Visual ++ .

, , promises . , , , .


:

// To see the problem also with Visual C++, use that compiler /Za option.
#include <iostream>
#include <string>
using namespace std;

void goodwrite( const string& s ) { cout << s << '\n'; }

void badwrite( string& s ) { cout << s << '\n'; }

auto main() -> int
{
    // Good:
    goodwrite( "The answer is " + to_string( 6*7 ) + "." );

    //! Uh oh, doesn't compile with standard C++:
    badwrite( "The answer is " + to_string( 6*7 ) + "." );
}
+2

const , - . const - const s, , .

0

"const".

"const" , . , , , .

, , .

0

TL; DR: .


const const, :

class A {
    int i = 10;
    mutable int j = 10;         // Explicitly allowed to change even for const objects

public:
    void f() { ++i; }           // OK: non-const function changes object
    void g() const { ++i; }     // Error: const function changes object
    int h() const { return i; } // OK: const function doesn't change object
    int s() const { return ++j; } // OK: const function changes mutable field 
};

void foo(const A& a) {
    a.f();      // Error: only const methods are allowed
    a.g(); a.h(); a.j(); // OK
}

, i foo, A h() s().

, , :

void foo(A a);
bool is_pal(std::string s);

, :

void foo(A& a);
bool is_pal(std::string& s);

And to make sure that the object will have the same state as it was before your function call, you need to add a constqualifier to it . This idiom is explained in Scott Meyers' book, Effective C ++ Third Edition, Point 20: Assume pass-by-reference-to-const to pass by value.

0
source

Source: https://habr.com/ru/post/1584994/


All Articles