本文介绍了在C ++中返回局部变量(有效C ++中的规则21,第3版)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,从C ++中的函数返回局部变量是不安全的,由于范围。
在Effective C ++ Third Edition中,Scott Meyers在第21页第101页讲述了这个问题。但是,他总结说,正确的决定是写:

  inline const Rational运算符*(const Rational& lhs,const Rational& rhs){
return Rational(lhs.n * rhs.h,lhs.d * rhs .d);
}

这不是一个不好的做法, / p>

UPD:感谢大家解释。

解决方案

实际返回一个局部变量。您可以返回局部变量的,或指向它的指针(即其地址)或对其的引用。



返回局部变量的是完全安全的:

  int good_func(){
int local = 42;
return local; //返回值local的副本
}

返回 >指针引用到局部变量是不安全的,因为变量在函数终止时不再存在:

  int * bad_func(){
int local = 42;
return& local; //返回指向local的指针
}

除了C没有C ++风格的引用。)


As known, returning local variable from function in C++, is unsafe, due to scoping.In Effective C++ Third Edition, Scott Meyers tells about this problem in item 21, at page 101. However, in conclusion he said, that right decision will be to write:

inline const Rational operator*(const Rational& lhs, const Rational& rhs) {
    return Rational(lhs.n * rhs.h, lhs.d * rhs.d);
}

Isn't this also a bad practice, and this function is unsafe?

UPD: Thanks everybody for explanation.

解决方案

You can't actually return a local variable. You can return the value of a local variable, or a pointer to it (i.e., its address), or a reference to it.

Returning the value of a local variable is perfectly safe:

int good_func() {
    int local = 42;
    return local; // returns a copy of the value of "local"
}

Returning a pointer or reference to a local variable is unsafe, because the variable ceases to exist when the function terminates:

int* bad_func() {
    int local = 42;
    return &local; // returns a pointer to "local"
}

(The same applies in C, except that C doesn't have C++-style references.)

这篇关于在C ++中返回局部变量(有效C ++中的规则21,第3版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 13:13