【发布时间】:2019-12-05 15:04:01
【问题描述】:
考虑以下两个函数:
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 更改,因此编译器应该仍然能够像调用 foo2(a) 一样直接传递 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 or no const,你还是按值传递,所以这里编译器不做这个优化也没有错。如果你足够疯狂地传递 (const) 值然后将 const 去掉怎么办?无论如何,为什么要这样做并指望编译器为您优化呢?为什么不像第二个例子那样直接通过 ref 传递?
标签: c++ parameter-passing constants pass-by-reference copy-constructor