c++ - 为什么即使参数标记为 'const' 也会调用复制构造函数?

标签 c++ parameter-passing constants pass-by-reference copy-constructor

考虑以下两个函数:

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&)

我猜答案与 constfoo 的定义中被删除有关,但我不知道为什么。对不起,如果我遗漏了一些明显的东西。

谢谢!

最佳答案

对于非引用参数,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/

相关文章:

c++ - 接受 N 个转换为相同类型的参数

c# - C#中按输出和按引用传递参数有什么区别

javascript - 将使用 $.get() 呈现的部分 View 中的任何数据传递到 ContentPage

c++ - C++ 中嵌套模板函数的 const 限定符

string - 为什么使用 const 字符串参数时程序会崩溃?

c++ - #define 到底有什么用?

c++ - C++ 中隐式默认构造函数的默认值

c++ - 对成员模板函数的访问控制

C++,Visual Studio 2015, vector 迭代器不可取消引用

JavaScript:将参数传递给回调函数