更改const std :: string引用的引用

时间:2011-07-03 07:45:27

标签: c++ reference const

我正在玩C ++中的引用,并注意到一些我无法解释的奇怪行为。我的理解是,如果我有一个非const变量和一个const引用同一个变量,然后修改非const变量,引用应该反映该修改。

示例:

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

为我生成以下输出:

x = 10
y = 10

但是,如果我将类型更改为std :: string,则const引用似乎不会反映修改后的变量:

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;
}

为我生成以下内容:

x = xyz
y = abc

使用std :: string尝试此操作时这是正常的预期行为吗? (我正在使用GCC 4.6.0;我目前没有任何其他编译器,所以我不知道这是否只发生在这个特定版本上。)

2 个答案:

答案 0 :(得分:10)

完全正常,就像我预期with GCC 4.3.44.5.1以及离线MSVC 10一样。您没有向我们展示您执行它的代码,或者4.6中存在错误。 0,我不相信。您确定在实际代码中实际使用的是引用而不只是const std::string吗?

答案 1 :(得分:1)

使用其他程序检查源文件,您可能在没有&amp;或某种编码问题的情况下意外保存了该文件。坦率地说,我怀疑GCC中是否存在这种大小的错误。事实上,我怀疑这种行为是否可行。

使用以下配置按预期工作:

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) 
相关问题