我试图从 [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/