What are the differences between swap in C++ and Python?

前端 未结 4 1532
北荒
北荒 2021-01-21 20:50

About swap, in C++, we can swap two by std::swap(x, y);. x and y are passed into swap as reference.

But

4条回答
  •  不思量自难忘°
    2021-01-21 21:24

    I don't believe that it is possible to simply implement the equivalent of C++'s swap in Python.

    This is due to the fundamental differences between the C++ object model and the Python object model. In python all variables reference objects. With the swap that you have implemented, all that happens is the the objects referred to by the two variables are exchanged. The objects themselves are untouched so nothing referring to the existing objects will see any change.

    In C++'s std::swap, the values of the two objects are exchanged so any expression denoting either of the objects being swapped will see the changes.

    >>> c = [ "hello", "world" ]
    >>> d = []
    >>> a = c
    >>> b = d
    >>> a, b = swap_in_python(a, b)
    >>> c
    ['hello', 'world']
    >>> d
    []
    >>>
    

    vs

    std::list c, d;
    c.push_back("hello");
    c.push_back("world");
    std::list &a = c, &b = d;
    std::swap( a, b ); // c is empty, d is "hello", "world"
    

提交回复
热议问题