Tomilov Anatoliy
Tomilov Anatoliy

Reputation: 16711

Warning when rvalue-declared variable goes out of scope being not moved from

Is there a way to make a compiler (clang++ or g++) to inform one about next situations:

static_assert(!std::is_lvalue_reference< T >::value);
void g(T);
void f(T x)
{
    T y = x;
#if 0 // turns warning off
    g(std::move(x));
#endif
} // warning here: x goes out of scope, but not moved from

or

static_assert(!std::is_reference< T >::value);
T f()
{
    T x;
    T y = x;
#if 0 // turns warning off
    return x;
#else
    return {};
#endif
} // warning here: x goes out of scope, but not moved from

Another class of warnings should be triggered, when moved from variable used once again:

void f()
{
    T x;
    T y = std::move(x);
    T z = x; // warning here: x is used since it has been moved from
}

Variables of such non-copyable classes as std::unique_ptr are rarely reused after their content has been stealed.

It would be great, if warnings described above would be available as per-variable triggered via #pragma or attribute or globally for all variables which types are classes with custom move-assignment operator and constructor.

Sometimes it is hard to follow the lifetime of variable.

There is SSA-form (static single assignment form) of intermediate representation (like AST) used in modern compilers. So I think it is not too hard for compilers to detect above situations.

Upvotes: 2

Views: 208

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

No, there is no way to do this with GCC or Clang today.

The new [[nodiscard]] attribute coming to C++17 is vaguely related, but not the same and can't be used for any of your cases.

Upvotes: 2

Related Questions