Does C++11 change the behavior of explicitly calling std::swap to ensure ADL-located swap's are found, like boost::swap?

后端 未结 4 1716
孤街浪徒
孤街浪徒 2020-12-01 10:32

Background

Consider for this question the following code:

#include 

namespace ns
{
    struct foo
    {
        foo() : i(0) {}
              


        
4条回答
  •  [愿得一人]
    2020-12-01 10:59

    I would have had to vote against your proof-of-concept implementation had it been proposed. I fear it would break the following code, which I'm pretty sure I've seen in the wild at least once or twice over the past dozen years.

    namespace oops
    {
    
        struct foo
        {
            foo() : i(0) {}
            int i;
    
            void swap(foo& x) {std::swap(*this, x);}
        };
    
        void swap(foo& lhs, foo& rhs)
        {
            lhs.swap(rhs);
        }
    
    }
    

    Whether you think the above is good code or bad, it works as the author intends in C++98/03 and so the bar for silently breaking it is pretty high. Telling users that in C++11 they would no longer have to write using std::swap; isn't a sufficiently high benefit to outweigh the disadvantage of silently turning the above code into infinite recursion.

    Another way to get out of writing using std::swap; is to use std::iter_swap instead:

    template 
    void do_swap(T& lhs, T& rhs)
    {
        std::iter_swap(&lhs, &rhs); // internally does what do_swap did above
    }
    

提交回复
热议问题