Weekly Quiz number: 5

Solve the quiz and collect tokens!

Type your nickname in the field below before submitting your solution. If you select the correct answer and submit it with your nick-name a token will be generated for you. Collect tokens and the corresponding nickname(s). If you get at least 10 of them you might be rewarded ;-)


Coding Quiz: Fun with std::move()

It may surprise you but std::move() doesn't actually move anything. It is just a type cast that converts any object into a Rvalue reference.

    template< class T >
    constexpr std::remove_reference_t<T>&& move( T&& t ) noexcept {
        return static_cast<std::remove_reference_t<T>&&>(t);
    }

std::move() converts a value into an Xvalue, marking it as safe to move. The actual move happens in the move constructor or move assignment operator, which transfers resources from source to destination.

Question 1

void consume(std::vector<int>&& vec);
void consume(const std::vector<int>& vec);
void foo() {
    const std::vector<int> data = getData();
    consume(std::move(data));
}
data will be moved into consume()
data will be copied into consume()

Question 2

std::string createString() {
    std::string result{"expensive data"};
    return std::move(result);
}

Is std::move needed here to make the compiler produce efficient code?

Yes, std::move() ensures that result is moved out of the function.
No, the compiler is able to optimize the return value. Just return result;.

Question 3

struct MoveableData;  // data is moveable
void foo() {
    vector<MoveableData> source = getData();
    vector<MoveableData> dest;
    for (const auto& data : source) {
        dest.push_back(std::move(data));
    }
}
The data will be moved from source to dest.
The data will be copied from source to dest.

Make sure your nickname contains at least 8 characters and is a unique as possible.




Disclaimer: