考虑以下两个函数:
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
的定义中被删除有关,但我不知道为什么。对不起,如果我遗漏了一些明显的东西。
谢谢!
最佳答案
对于非引用参数,const
在编译器存储函数签名时实际上被忽略了。例如,给出这个函数原型(prototype):
void func(std::string);
func
可以用这个签名实现:
void func(const std::string) // This is NOT an overload.
{}
因此 const
对值参数的传递方式没有任何影响。它们被复制。 const
仅影响参数在函数实现中的使用方式。
关于c++ - 为什么即使参数标记为 'const' 也会调用复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57234085/