Changing the reference referent const std :: string

I play with C ++ links and notice a bit strange behavior that I cannot explain. I understand that if I have a non-constant variable and a constant refers to the same variable, and then change the non-constant variable, the link should reflect this 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 does not reflect the changed 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 usual expected behavior when trying to do this with std :: string? (I am using GCC 4.6.0, I don't have another compiler at the moment, so I donโ€™t know if this only happens with this particular version or not.)

+6
source share
2 answers

It works just fine and exactly as expected for me with GCC 4.3.4 and 4.5.1 , and also offline with MSVC 10. You donโ€™t show us the code you are running, or there is an error in 4.6.0 that I donโ€™t I believe. Are you really using a link, not just const std::string in your real code?

+10
source

Check the source file with some other program, maybe you accidentally saved it without a problem with the & symbol, or some encoding problem. Honestly, I doubt a bug of this size will ever exist in GCC. In fact, I doubt that this behavior will even be possible.

Works as expected with the following configuration:

 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) 
+1
source

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


All Articles