问题描述
我正在实现一些C ++静态分析规则,其中之一禁止某个函数返回对该函数的参考参数的引用或指针,即以下所有条件都不符合:
I'm implementing some C++ static analysis rules, and one of them prohibits a function from returning a reference or pointer to a reference parameter of the function, i.e. the following are all non-compliant:
int *f(int& x) { return &x; } // #1
const int *g(const int& x) { return &x; } // #2
int& h(int& x) { return x; } // #3
const int& m(const int& x) { return x; } // #4
给出的理由是无论引用参数是临时对象还是对该参数的引用,都是实现定义的行为."
The justification given for this is that "It is implementation-defined behaviour whether the reference parameter is a temporary object or a reference to the parameter."
但是,我对此感到困惑,因为C ++中的流运算符是以这种方式编写的,例如
I'm puzzled by this, however, because stream operators in C++ are written in this way, e.g.
std::ostream& operator<<(std::ostream& os, const X& x) {
//...
return os;
}
我认为我非常有信心C ++中的流运算符通常不会表现出实现定义的行为,那么到底是怎么回事?
I think I'm pretty confident that stream operators in C++ do not in general exhibit implementation-defined behaviour, so what's going on?
根据我目前的理解,我希望#1和#3定义明确,因为临时对象不能绑定到非const引用,因此int& x
引用一个实物它的生存期超出了函数的范围,因此返回指向该对象的指针或引用就可以了.我希望#2会比较狡猾,因为可能会将const int& x
绑定到一个临时目录,在这种情况下,尝试获取其地址似乎是一个错误的计划.我不确定#4-我的直觉是那也很容易躲闪,但我不确定.特别是,我不清楚在以下情况下会发生什么情况:
According to my understanding as it is at present, I would expect #1 and #3 to be well-defined, on the basis that temporaries cannot be bound to non-const references, so int& x
refers to a real object that has lifetime beyond the scope of the function, hence returning a pointer or reference to that object is fine. I would expect #2 to be dodgy, because a temporary could have been bound to const int& x
, in which case trying to take its address would seem a bad plan. I'm not sure about #4 - my gut feeling is that that's also potentially dodgy, but I'm not sure. In particular, I'm not clear on what would happen in the following case:
const int& m(const int& x) { return x; }
//...
const int& r = m(23);
推荐答案
您说过,#1和#3很好(尽管#1可以说是不好的风格).
As you say, #1 and #3 are fine (though #1 is arguably bad style).
由于#2相同的原因,#4令人迷惑.它允许传播对const的引用,超过其生存期的临时对象.
#4 is dodgy for the same reason #2 is; it allows propagating a const reference to a temporary past its lifetime.
让我们检查一下:
#include <iostream>
struct C {
C() { std::cout << "C()\n"; }
~C() { std::cout << "~C()\n"; }
C(const C &) { std::cout << "C(const C &)\n"; }
};
const C &foo(const C &c) { return c; }
int main() {
const C &c = foo(C());
std::cout << "c in scope\n";
}
这将输出:
C()
~C()
c in scope
这篇关于这个C ++静态分析规则照原样有意义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!