Timothy Liu
Timothy Liu

Reputation: 406

Is it ok to cast a temporary object to rvalue reference and then cast it to lvalue reference to discard lvalue reference parameters of a function?

There's a function with an lvalue reference as a parameter:

using Vec = std::vector<int>;
void func(int n, Vec& log) {
    some_actions(n);
    log.push_back(n);
}

And I want to discard the parameter log here when I call it, but I don't want to create a new variable like:

Vec temp;
func(1, temp);

And I fount that the following code can pass the compilation:

func(1, (Vec&)(Vec&&)Vec{});
// or
func(1, reinterpret_cast<Vec&>(static_cast<Vec&&>(Vec{})));

Is it OK in C++? Are there any undefined behaviors?

And is it a good practice?

Upvotes: 1

Views: 82

Answers (0)

Related Questions