丢失'const'修饰符

时间:2012-04-24 16:26:32

标签: c++

  

可能重复:
  constant references with typedef and templates in c++

请查看以下代码:

typedef wstring& RT;
RT Change(const RT v)
{
    v += L"234"; // why can I change this argument???

    return v;
}

int _tmain(int argc, _TCHAR* argv[])
{    
    wstring str = L"111";
    wstring &str2 = Change(str);

    return 0;
}

我很惊讶这个论点' v'在'变化'功能可以改变。我们失去了' const'修改。诸如std :: add_const之类的元函数没有帮助,你能解释一下这种行为吗?

工具:VS2010

1 个答案:

答案 0 :(得分:4)

它有点像表达式中的优先级。当你说

const wstring & foo;

它使foo成为对常量wstring的引用。你可以这样想:

(const wstring) & foo;

当你创建一个typedef时,你已经有效地改变了优先级。

const RT foo;
const wstring & foo;  // not equivalent, RT is a typedef, not a macro
const (wstring &) foo;  // this is effectively what happens

const使foo为const,而不是foo引用的内容。

当然,正如FredOverflow指出的那样,const引用是多余的,因为您不能将引用分配给它引用的对象。因此,结果是foo只是一个简单的旧参考。