简体   繁体   English

我是真的返回地址还是提及临时地址

[英]Am I really returning address or reference to a temporary

I am implementing a generic function that finds minimum in an array. 我实现了一个通用函数,该函数在数组中找到最小值。 It works fine and looks like this: 它工作正常,看起来像这样:

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;
}

But in the IDE, I get a warning: returning address or reference to a temporary . 但是在IDE中,我得到一个警告: returning address or reference to a temporary If I change TempMin to input[leastIndex] , then the warning disappears. 如果将TempMin更改为input[leastIndex] ,则警告消失。

I am wondering that I tend to return by value and also I haven't used & anywhere, but why does it still return by reference or address? 我想知道我倾向于按值返回,而且我也没有在任何地方使用& ,但是为什么它仍按引用或地址返回?

Thoughts? 思考?

Thanks. 谢谢。

EDIT 编辑

In decltype(input[0]) , I have passed a subscript to input array. decltype(input[0]) ,我将下标传递给输入数组。 So shouldn't it really correspond to a value and not a reference or address to a temporary? 因此,它不应该真正对应于一个值,而不是对应于一个临时的引用或地址吗?

As "Effective Modern C++" says: 正如“有效的现代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. 在C ++ 11中,decltype的主要用途是声明函数模板,其中函数的返回类型取决于其参数类型。 For example, suppose we'd like to write a function that takes a container that supports indexing via square brackets (ie, 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&. T类型的对象容器上的operator []通常返回T&。 This is the case for std::deque, for example, and it's almost always the case for std::vector. 例如,std :: deque就是这种情况,而std :: vector几乎总是这种情况。 For std::vector, however, operator[] does not return a bool&. 但是,对于std :: vector,operator []不会返回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. 相反,它返回一个全新的对象…… 但是这里重要的是容器的operator []返回的类型取决于容器。

So this code: 所以这段代码:

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

auto maybe T&. auto也许T&。

And this code: 这段代码:

auto temp = input[0]

auto maybe T. auto也许T。

I think the compiler hints you, maybe that's the reason. 我认为编译器会提示您,也许这就是原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM