Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing referent of const std::string reference

I'm playing around with references in C++, and noted a bit of odd behavior that I am unable to explain. My understanding is that if I have a non-const variable and a const reference to that same variable and then modify the non-const variable, the reference should reflect that modification.

Example:

void foo() {
    int x = 5;
    const int& y = x;
    x = 10;
    std::cout << "x = " << x << std::endl;
    std::cout << "y = " << y << std::endl;
}

produces the following output for me:

x = 10
y = 10

However, if I change the type to std::string, the const reference doesn't seem to reflect the modified variable:

void foo() {
    std::string x = "abc";
    const std::string& y = x;
    x = "xyz";
    std::cout << "x = " << x << std::endl;
    std::cout << "y = " << y << std::endl;
}

produces the following for me:

x = xyz
y = abc

Is this the normal expected behavior when attempting this with std::string? (I'm using GCC 4.6.0; I don't have any other compiler available at the moment, so I don't know if this is only happening with this specific version or not.)

like image 826
Bobby Avatar asked Jul 03 '11 07:07

Bobby


People also ask

Can you reassign a const reference?

Const Reference to a pointer is a non-modifiable value that's used same as a const pointer. Here we get a compile-time error as it is a const reference to a pointer thus we are not allowed to reassign it.

Can you change a reference CPP?

This is not possible, and that's by design. References cannot be rebound. You are not changing the reference, you are assigning the value of k to the object referred to by x . After this assignment, a == k , and x still refers to a .

What is the difference between const reference and reference?

A const reference is actually a reference to const. A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it's a reference to const. Once a reference is bound to refer to an object, it can not be bound to refer to another object.

Can a const reference refer to a non const object?

No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .


1 Answers

Works totally fine and just as expected for me with GCC 4.3.4 and 4.5.1 aswell as offline with MSVC 10. You are not showing us the code you execute it seems, or there is a bug in 4.6.0 which I don't believe. Are you sure you're actually using a reference and not just a const std::string in your real code?

like image 154
Xeo Avatar answered Oct 17 '22 06:10

Xeo