WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Advanced · question 48 of 100

Explain the concept of perfect forwarding in C++ and its benefits.?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

Perfect forwarding is a C++ technique that allows functions to pass arguments through to other functions with minimal overhead and without losing any information about the original arguments. The idea behind perfect forwarding is to preserve the exact type and value category of the arguments being passed.

In order to achieve perfect forwarding, C++ uses two types of references: rvalue references and forwarding references (also known as universal references). Rvalue references are used to refer to temporary objects or values that can be moved, while forwarding references are used to refer to any type of value.

Here’s an example of perfect forwarding:

    template<typename T>
    void forwarder(T&& arg)
    {
        target(std::forward<T>(arg));
    }
    
    void target(int& arg)
    {
        std::cout << "Lvalue: " << arg << std::endl;
    }
    
    void target(int&& arg)
    {
        std::cout << "Rvalue: " << arg << std::endl;
    }
    
    int main()
    {
        int lvalue = 42;
        forwarder(lvalue); // calls target(int&)
        forwarder(123);    // calls target(int&&)
    }

In this example, the forwarder function takes a forwarding reference as its argument, which can bind to any type of value. Inside the forwarder function, the std::forward function is used to forward the argument to the target function with the correct value category (either lvalue or rvalue).

The target function is overloaded to take both lvalue and rvalue references, and prints a message indicating whether it received an lvalue or an rvalue. The forwarder function calls the target function with the argument passed to it, preserving its original value category.

The benefit of perfect forwarding is that it allows functions to pass arguments to other functions without losing any information about the original argument. This can be useful in a variety of situations, such as when implementing forwarding constructors or when passing arguments to generic functions that need to preserve the type and value category of the original arguments.

Overall, perfect forwarding is an important technique in modern C++ programming that enables efficient and flexible argument passing between functions.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics