简体   繁体   中英

Does swap() cause undefined behaviour?

I'm trying to understand the conditions on std::swap from [C++11: utility.swap]. The template is defined as

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

(plus some noexcept details) and as having the effect of "exchanging the values stored at the two locations".

Is the following program have well-defined?

#include <utility>

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

If I wrote swap code myself (ie int tmp = m; m = n; n = tmp; ), it would have undefined behaviour, since it would attempt lvalue-to-rvalue conversion on an uninitialized object. But the standard std::swap function does not seem to come with any conditions imposed on it, nor can one derive from the specification that there is any lvalue-to-rvalue and thus UB.

Does the standard require std::swap to perform some magic that is well-defined on uninitialized objects?

To clarify the point, consider the function void f(int & n) { n = 25; } void f(int & n) { n = 25; } , which never has undefined behaviour (since it does not read from n ).

Very nice question. However, I would say this is covered by [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.

To address your concern about f(n) , the function f from your question is not a part of the C++ standard library and thus the above clause does not apply to it.

As the value of M is undefined, I would expect it to taint the call to swap. Nasal Demons may fly, when swap is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM