C++ Interview Questions

22 Questions
C++ Programming

C++ Programming

Embedded SystemsIoTOther

Question 7

What is a move constructor in C++?

Answer:

A move constructor in C++ is a special constructor that enables the transfer of resources from a temporary (or "r-value") object to a new object, rather than copying the resources. Introduced in C++11, move constructors are part of move semantics, which optimize performance by eliminating unnecessary deep copies of resources, such as dynamic memory.

Purpose of Move Constructor:
The primary purpose of a move constructor is to "move" resources from one object to another, thereby avoiding the performance overhead associated with deep copying. This is particularly useful when dealing with large objects or resources like dynamic memory, file handles, or network connections. Move constructors provide an efficient way to transfer ownership of these resources.

Syntax of Move Constructor:
A move constructor takes an r-value reference to another object of the same type. The syntax for declaring a move constructor is:

ClassName(ClassName&& other);

Here, ClassName&& is an r-value reference to an object of type ClassName.

Example:
Let's consider a class MyClass that manages a dynamically allocated array. We will implement a move constructor to efficiently transfer the resources.

#include <iostream>
#include <utility> // for std::move

class MyClass {
private:
    int* data;
    size_t size;
public:
    // Constructor
    MyClass(size_t n) : size(n) {
        data = new int[n];
        std::cout << "Constructor called\n";
    }

    // Destructor
    ~MyClass() {
        delete[] data;
        std::cout << "Destructor called\n";
    }

    // Copy Constructor
    MyClass(const MyClass& other) : size(other.size) {
        data = new int[other.size];
        std::copy(other.data, other.data + other.size, data);
        std::cout << "Copy Constructor called\n";
    }

    // Move Constructor
    MyClass(MyClass&& other) noexcept : data(nullptr), size(0) {
        // Transfer ownership of the resource
        data = other.data;
        size = other.size;

        // Nullify the source object's pointers
        other.data = nullptr;
        other.size = 0;

        std::cout << "Move Constructor called\n";
    }

    // Copy Assignment Operator
    MyClass& operator=(const MyClass& other) {
        if (this == &other) {
            return *this;
        }
        delete[] data;
        size = other.size;
        data = new int[other.size];
        std::copy(other.data, other.data + other.size, data);
        std::cout << "Copy Assignment called\n";
        return *this;
    }

    // Move Assignment Operator
    MyClass& operator=(MyClass&& other) noexcept {
        if (this == &other) {
            return *this;
        }
        delete[] data;
        data = other.data;
        size = other.size;
        other.data = nullptr;
        other.size = 0;
        std::cout << "Move Assignment called\n";
        return *this;
    }

    // Display the data
    void display() const {
        for (size_t i = 0; i < size; ++i) {
            std::cout << data[i] << " ";
        }
        std::cout << "\n";
    }
};

int main() {
    MyClass obj1(10);
    MyClass obj2(std::move(obj1)); // Move Constructor is called

    MyClass obj3(5);
    obj3 = std::move(obj2); // Move Assignment is called

    return 0;
}

Explanation:

  1. Move Constructor: The move constructor transfers ownership of resources from the other object to the new object. It takes an r-value reference (MyClass&& other) and uses std::move to transfer the resource.

    • It transfers the data pointer and size from the other object.
    • It nullifies the other object's pointers to avoid double deletion.
    • The noexcept specifier indicates that the move constructor does not throw exceptions, which can help optimize certain operations.
  2. Move Assignment Operator: Similar to the move constructor, the move assignment operator transfers resources from one object to another, but it operates on an existing object rather than a new one.

    • It first deletes any existing resources of the current object.
    • It then transfers the resources from the other object.
    • It nullifies the other object's pointers.

Benefits of Move Constructors:

  • Performance Optimization: Move constructors significantly reduce the overhead of copying large objects, leading to more efficient code.
  • Resource Safety: By transferring ownership and nullifying the source object, move constructors help ensure that resources are correctly managed and deallocated.

Summary:
Move constructors in C++ provide an efficient way to transfer resources from temporary objects, avoiding the performance cost of deep copying. They are a key part of move semantics, enhancing both the performance and safety of C++ programs. Implementing move constructors and move assignment operators allows developers to create more efficient and robust classes, especially when dealing with dynamic memory and other resources.

Recent job openings