考虑以下两个函数:
int foo(const std::string x) {
return x.length();
}
int foo2(const std::string& x2) {
return x2.length();
}
当调用时
std::string a("hello world!");
foo(a);
编译器似乎仍会将临时对象(通过复制构造函数创建)传递给
foo
(https://godbolt.org/z/p2ID1d)。为什么会这样?因为x是const的,因此不会被foo
更改,因此编译器应该仍然能够直接传递a
,就像调用foo2(a)
时一样。顺便提一下:我正在查看godbolt生成的函数类型:foo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)
foo2(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
我猜这个问题与
const
在定义函数 foo
时被删除有关,但我不知道为什么。如果我漏掉了什么显而易见的东西,对不起。谢谢!