gpt4 book ai didi

c++ - 我真的是返回地址或引用临时

转载 作者:行者123 更新时间:2023-11-30 05:46:14 25 4
gpt4 key购买 nike

我正在实现一个在数组中查找最小值的通用函数。它工作正常,看起来像这样:

template<typename T>
auto FindMinimum(T &input, int size) -> decltype(input[0])
{
auto TempMin=input[0];
int leastIndex=0;
for (int i = 1; i < size ; i++)
{
if(input[i]<TempMin)
{
leastIndex=i;
TempMin=input[i];
}
}

return TempMin;
}

但在 IDE 中,我收到警告:returning address or reference to a temporary 。如果我将 TempMin 更改为 input[leastIndex],则警告消失。

我想知道我倾向于按值返回,而且我没有在任何地方使用 &,但为什么它仍然按引用或地址返回?

想法?

谢谢。

编辑

decltype(input[0]) 中,我将下标传递给输入数组。那么它真的不应该对应于一个值而不是一个临时的引用或地址吗?

最佳答案

正如“Effective Modern C++”所说:

In C++11, perhaps the primary use for decltype is declaring function templates where the function’s return type depends on its parameter types. For example, suppose we’d like to write a function that takes a container that supports indexing via square brackets (i.e., the use of “[] ”) plus an index, then authenticates the user before returning the result of the indexing operation. The return type of the function should be the same as the type returned by the indexing operation.

operator[] on a container of objects of type T typically returns a T&. This is the case for std::deque, for example, and it’s almost always the case for std::vector. For std::vector, however, operator[] does not return a bool&. Instead, it returns a brand new object ...but what’s important here is that the type returned by a container’s opera tor[] depends on the container.

所以这段代码:

template<typename T>
auto FindMinimum(T &input, int size) -> decltype(input[0])

auto 可能是 T&。

还有这段代码:

auto temp = input[0]

auto 可能是 T。

我想编译器会提示你,也许这就是原因。

关于c++ - 我真的是返回地址或引用临时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29003335/

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