c++ - swap() 会导致未定义的行为吗?

标签 c++ c++11 language-lawyer undefined-behavior lvalue-to-rvalue

我试图从 [C++11:utility.swap] 中了解 std::swap 的条件。模板定义为

template <typename T> void swap(T &, T &)

(加上一些 noexcept 细节)并具有“交换存储在两个位置的值”的效果。

以下程序是否定义明确?

#include <utility>

int main()
{
    int m, n;
    std::swap(m, n);
}

如果我自己编写交换代码(即 int tmp = m; m = n; n = tmp;),它将具有未定义的行为,因为它会尝试左值到右值的转换一个未初始化的对象。但是标准的 std::swap 函数似乎没有附加任何条件,也不能从规范中得出存在任何左值到右值和因此 UB 的规范。

标准是否要求 std::swap 对未初始化的对象执行一些明确定义的魔法?

为了澄清这一点,请考虑函数 void f(int & n) { n = 25; },它永远不会有未定义的行为(因为它不是从 n 读取的)。

最佳答案

非常好的问题。但是,我会说 [res.on.arguments]§1 涵盖了这一点:

Each of the following applies to all arguments to functions defined in the C++ standard library, unless explicitly stated otherwise.

  • If an argument to a function has an invalid value (such as a value outside the domain of the function or a pointer invalid for its intended use), the behavior is undefined.

为了解决您对 f(n) 的担忧,您问题中的函数 f 不是 C++ 标准库的一部分,因此上述条款不适用给它。

关于c++ - swap() 会导致未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24335886/

相关文章:

python - 'or' 是否用在赋值 pythonic 的右侧?

c++ - 在 Objective C 和 C++ 组合的 xcode 项目中链接 Boost

c++ - 逐成员连载

c++ - 使用 getline() 无限运行的匹配词 c++ 程序?

c++ - 如何像普通 C 函数一样使用正确的 'this' 指针调用 C++ 类成员函数? (指向类成员函数的指针)

c++ - std::condition_variable 和 std::condition_variable_any 有什么区别?

c++ - 是否允许编译器优化堆内存分配?

c++ - 为什么这个表达式不是常量表达式?

c++ - Qt中如何同步主线程和工作线程?

c++ - 从重载函数中提取返回类型