gpt4 book ai didi

c++ - 为什么数组会衰减到模板函数中的指针

转载 作者:可可西里 更新时间:2023-11-01 18:04:35 27 4
gpt4 key购买 nike

我不明白为什么数组会衰减为模板函数中的指针。

如果您查看以下代码:当参数被强制为引用(函数 f1)时,它不会衰减。在另一个函数 f 中,它会衰减。为什么函数 f 中 T 的类型不是 const char (buff&)[3] 而是 const char*(如果我理解正确的话)?

#include <iostream>

template <class T>
void f(T buff) {
std::cout << "f:buff size:" << sizeof(buff) << std::endl; //prints 4
}

template <class T>
void f1(T& buff) {
std::cout << "f:buff size:" << sizeof(buff) << std::endl; //prints 3
}

int main(int argc, char *argv[]) {
const char buff[3] = {0,0,0};
std::cout << "buff size:" << sizeof(buff) << std::endl; //prints 3
f(buff);
f1(buff);
return 0;
}

最佳答案

这是因为数组不能按值传递给函数。因此,为了使其工作,数组衰减为一个指针,然后该指针按值传递给函数。

换句话说,按值传递数组类似于用另一个数组初始化一个数组,但在 C++ 中一个数组不能初始化 使用另一个数组:

char buff[3] = {0,0,0};
char x[3] = buff; //error

因此,如果一个数组出现在 = 的右侧,则左侧必须是 pointerreference 类型:

char *y = buff; //ok - pointer
char (&z)[3] = buff; //ok - reference

演示:http://www.ideone.com/BlfSv

正是出于同样的原因,auto 在下面的每种情况下都有不同的推断(请注意,auto 随 C++11 一起提供):

auto a = buff; //a is a pointer - a is same as y (above)
std::cout << sizeof(a) << std::endl; //sizeof(a) == sizeof(char*)

auto & b = buff; //b is a reference to the array - b is same as z (above)
std::cout << sizeof(b) << std::endl; //sizeof(b) == sizeof(char[3])

输出:

4 //size of the pointer
3 //size of the array of 3 chars

演示:http://www.ideone.com/aXcF5

关于c++ - 为什么数组会衰减到模板函数中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7797839/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com