返回地址或局部变量或临时 C++ 警告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3870649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:56:36  来源:igfitidea点击:

returning address or local variable or temporary C++ warning

c++warnings

提问by limlim

Possible Duplicate:
c++ warning: address of local variable

可能重复:
C++ 警告:局部变量的地址

Hi, When i write this code:

嗨,当我写这段代码时:

//Returns the transpose matrix of this one
SparseMatrix& SparseMatrix::transpose()const{
    vector<Element> result;
    size_t i;
    for(i=0;i<_matrix.size();++i){
        result.push_back(Element(_matrix.at(i)._col, _matrix.at(i)._row, _matrix.at(i)._val));
    }

    return SparseMatrix(numCol,numRow,result);
}

I get the warning "returning address or local variable or temporary". The last line calls the SparseMatrix constructor. I don't understand what's wrong with this code, and how can i fix it so i can return a SparseMatrix object as i want.

我收到警告“返回地址或局部变量或临时”。最后一行调用 SparseMatrix 构造函数。我不明白这段代码有什么问题,我该如何修复它以便我可以根据需要返回 SparseMatrix 对象。

回答by RichieHindle

You're returning a reference, not an actual object - note the &here:

您返回的是引用,而不是实际对象 - 请注意&此处:

SparseMatrix& SparseMatrix::transpose()const{

If you want to return the actual object, remove that &.

如果要返回实际对象,请将其删除&

The last line does indeed call the constructor, but it doesn't return the resulting object. That object immediately gets destroyed, and an invalid reference to it gets returned.

最后一行确实调用了构造函数,但它不返回结果对象。该对象立即被销毁,并返回对它的无效引用。

回答by xtofl

In C++, local variables are 'automatically' destructed when going out of scope. Your returnstatement will create a nameless, temporary variable of type SparseMatrixthat will immediately go out of scope. Hence, returning a reference to it doesn't make sense.

在 C++ 中,局部变量在超出范围时会“自动”销毁。您的return语句将创建一个无名的临时变量,SparseMatrix该变量将立即超出范围。因此,返回对它的引用没有意义。

It may be easier to return by value: then a copy of the temporary will be returned. The compiler can optimize that away (copy elision).

按值返回可能更容易:然后将返回临时副本。编译器可以优化它(复制省略)。

If you really want to pass an object out of a function, you should create it on the heap, using new:

如果你真的想从函数中传递一个对象,你应该在堆上创建它,使用new

SparseMatrix* SparseMartix::transopse()const{


     //...
     return new SparseMatrix(...);

}

But then, you need to take care of the lifetime of the returned object yourself.

但是,您需要自己处理返回对象的生命周期。

回答by Chubsdad

The construct 'T()' creates a temporary of type 'T' which is basically not an Lvalue (but an Rvalue).

构造 'T()' 创建了一个类型为 'T' 的临时变量,它基本上不是左值(而是右值)。

$12.1/11 - "A functional notation type conversion (5.2.3) can be used to create new objects of its type. [ Note: The syntax looks like an explicit call of the constructor.

12 An object created in this way is unnamed. [ Note: 12.2 describes the lifetime of >temporary objects. —end note ] [ Note: explicit constructor calls do not yield lvalues, see 3.10. —end note ] The lifetime of this temporary is the end of the full expression i.e. the ending semicolon after the expression.

$12.2/3 - "Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression."

$12.2/5- 'The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement."

$12.1/11 - “功能符号类型转换(5.2.3)可用于创建其类型的新对象。[注意:语法看起来像构造函数的显式调用。

12 以这种方式创建的对象是未命名的。[ 注意:12.2 描述了>临时对象的生命周期。—end note ] [ 注意:显式构造函数调用不会产生左值,参见 3.10。—end note ] 这个临时的生命周期是完整表达式的结尾,即表达式之后的结尾分号。

$12.2/3 - “临时对象被销毁作为评估完整表达式(1.9)(词法上)包含它们创建点的最后一步。即使该评估以抛出异常结束也是如此。值计算并且销毁临时对象的副作用仅与完整表达式相关,与任何特定子表达式无关。”

$12.2/5- '函数返回语句(6.6.3)中的返回值的临时绑定的生命周期没有延长;临时在 return 语句中的完整表达式结束时被销毁。”

Therefore your function tries to return a reference to a memory location whose storage duration is already over and the object has been destroyed.

因此,您的函数尝试返回对存储持续时间已经结束并且对象已被销毁的内存位置的引用。

Therefore a warning. Note that this situation is not required to be explicitly diagnosed by the Standard and hence a warning.

因此发出警告。请注意,这种情况不需要由标准明确诊断,因此是警告。