achieve non copying swap function

oneat

I want to create function like:

void func(sample &a){
    sample b();
    std::swap(b,a);
}

problem is that always when I use swap then copy constructor is used and destructor is applied on temporary object used in swap function.

Is there possibility to achieve non copying swap?

Tristan Brindle

The C++11 solution to your problem is to provide a move constructor and move-assignment operator in your sample class. Then, std::swap will use move rather than copy operations, which should be more efficient (you'll still see the destructor being called, but this will usually be on an "empty" object and should be very cheap).

Generally, if you're writing your own copy constructor and copy assignment operator then you also need to write a move constructor and move assignment operator (as well as a destructor of course) -- this is the "rule of 5" in C++11, which expands on the "rule of 3" known from C++98. For example, consider this (bad) example class which manually manages memory (N.B. this is just an example for exposition, in real life use std::vector or std::unique_ptr rather than doing this):

class example {
public:
    example() 
        : ptr{new int[1024]}
    {}

    example(const example& other)
        : ptr{new int[1024]}
    {
        // Copy other's member array
        std::copy(other.ptr, other.ptr + 1024, ptr);
    }

    example& operator=(const example& other)
    {
         if (this != &other) {
             std::copy(other.ptr, other.ptr + 1024, ptr);
         }
         return *this;
    }

    ~example()
    {
        delete[](ptr); 
    }

    example(example&& other)
        : ptr(other.ptr) // "steal" other's ptr
    {
        other.ptr = nullptr;
    }

    example& operator=(example&& other)
    {
        std::swap(ptr, other.ptr);
        return *this;
    }

private:
    int* ptr;
};

Now, when you std::swap two examples, the swap function will use move operations and no additional allocations will take place, just some (cheap) pointer swaps, and a no-op call to delete[](nullptr).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related