以下函数在 C++03 或 C++11 中是安全的还是表现出 UB?
string const &min(string const &a, string const &b) {
return a < b ? a : b;
}
int main() {
cout << min("A", "B");
}
返回对传递给函数的对象的引用是否可以 引用?
是否保证临时的
string
对象是 没被毁得太早?给定的函数有没有可能
min
可以展示 UB(如果它不在给定的上下文中)?是否可以做一个等效但安全的功能,同时仍然避免 复制还是移动?
最佳答案
Is it OK to return a reference to an object passed to the function by reference?
只要在您通过该引用访问对象之前未销毁该对象,就可以。
Is it guaranteed that the temporary
string
object is not destroyed too soon?
在这种情况下,是的。一个临时的持续到创建它的完整表达式的末尾,所以它不会被销毁,直到 在 被流式传输到 cout
。
Is there any chance that the given function min could exhibit UB (if it does not in the given context)?
是的,这是一个例子:
auto const & r = min("A", "B"); // r is a reference to one of the temporaries
cout << r; // Whoops! Both temporaries have been destroyed
Is it possible to make an equivalent, but safe function while still avoiding copying or moving?
我不这么认为;但只要您不保留对其结果的引用,此函数是安全的。
关于c++ - 通过函数传递引用安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16279390/