Bobby
Bobby

Reputation: 69

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.)

Upvotes: 6

Views: 381

Answers (2)

Frigo
Frigo

Reputation: 1724

Check the source file with some other program, you might have saved it accidentally without the &, or some kind of encoding issue. Frankly, I doubt an error of this size would ever exist in GCC. In fact, I doubt if this behavior would be even possible.

Works as expected here with the following config:

Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/4.5.2/lto-wrapper.exe
Target: mingw32
Configured with: ../gcc-4.5.2/configure --enable-languages=c,c++,ada,fortran,objc,obj-c++ --disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgomp --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific-runtime-libs --disable-werror --build=mingw32 --prefix=/mingw
Thread model: win32
gcc version 4.5.2 (GCC) 

Upvotes: 1

Xeo
Xeo

Reputation: 131779

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?

Upvotes: 10

Related Questions