c++ - 通过函数传递引用安全吗?

标签 c++ c++11

以下函数在 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/

相关文章:

c++ - 交换两个复杂结构的最快方法是什么?

c++ - 在 OSX 上与 C++ 中的 libconfig 链接

c++ - 使用 Ocilib 时填充字符串缓冲区

c++ - C++ 模板能否确定正在声明/定义的实例是否为常量?

c++ - 在STL算法中调用多个函数

c++ - 我可以避免通过 time_t 打印 time_point 吗?

c++ - 应用具有通用引用的 SFINAE 模式

C++ 在静态函数中访问私有(private)静态变量

c++ - 具有原始类型的模板 vector 类型

c++ - PoDoFo 从 pdf 中提取文本 + 坐标