Category: Programming

  • What Are the Main Differences Between the Different C++ Smart Pointers (`unique_ptr`, `shared_ptr`, `weak_ptr`)?

    C++ offers three main smart pointers: `unique_ptr`, `shared_ptr`, and `weak_ptr`. `unique_ptr` provides exclusive ownership and cannot be copied. `shared_ptr` allows multiple owners with reference counting. `weak_ptr` is used to break circular references and does not affect the reference count.

    Examples:

    #include 
    
    void uniquePointerExample() {
        std::unique_ptr ptr1(new int(10));
        // std::unique_ptr ptr2 = ptr1; // Error: cannot copy unique_ptr
    }
    
    void sharedPointerExample() {
        std::shared_ptr ptr1(new int(20));
        std::shared_ptr ptr2 = ptr1; // Allowed: both own the resource
    }
    
    void weakPointerExample() {
        std::shared_ptr ptr1(new int(30));
        std::weak_ptr weakPtr = ptr1; // weak_ptr does not own the resource
    }
  • How Do You Implement Custom Memory Allocators in C++?

    Custom memory allocators in C++ allow for more control over memory management. They can optimize allocation patterns specific to application needs. Custom allocators are useful for performance tuning and managing complex data structures.

    Example of a custom allocator:

    #include 
    #include 
    
    template 
    class MyAllocator : public std::allocator {
    public:
        T* allocate(size_t n) {
            std::cout << "Allocating " << n << " elements." << std::endl;
            return std::allocator::allocate(n);
        }
        void deallocate(T* p, size_t n) {
            std::cout << "Deallocating " << n << " elements." << std::endl;
            std::allocator::deallocate(p, n);
        }
    };
    
    int main() {
        std::vector> vec;
        vec.push_back(10);
        return 0;
    }
  • What Are Variadic Templates, and How Are They Used?

    Variadic templates allow you to create functions or classes that accept a variable number of template parameters. They enable more flexible and generic code. Variadic templates are useful for creating functions that work with different numbers of arguments.

    Example of variadic templates:

    #include 
    
    template 
    void print(T arg) {
        std::cout << arg << std::endl;
    }
    
    template 
    void print(T arg, Args... args) {
        std::cout << arg << " ";
        print(args...);
    }
    
    int main() {
        print(1, 2, 3.5, "hello");
        return 0;
    }