Skip to content
This repository was archived by the owner on Mar 28, 2020. It is now read-only.

Disallow ArrayRef assignment from temporaries. #28

Merged
merged 1 commit into from
Oct 12, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions include/llvm/ADT/ArrayRef.h
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,22 @@ namespace llvm {
return Data[Index];
}

/// Disallow accidental assignment from a temporary.
///
/// The declaration here is extra complicated so that "arrayRef = {}"
/// continues to select the move assignment operator.
template <typename U>
typename std::enable_if<std::is_same<U, T>::value, ArrayRef<T>>::type &
operator=(U &&Temporary) = delete;

/// Disallow accidental assignment from a temporary.
///
/// The declaration here is extra complicated so that "arrayRef = {}"
/// continues to select the move assignment operator.
template <typename U>
typename std::enable_if<std::is_same<U, T>::value, ArrayRef<T>>::type &
operator=(std::initializer_list<U>) = delete;

/// @}
/// @name Expensive Operations
/// @{
Expand Down
28 changes: 28 additions & 0 deletions unittests/ADT/ArrayRefTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,26 @@ static_assert(
!std::is_convertible<ArrayRef<volatile int *>, ArrayRef<int *>>::value,
"Removing volatile");

// Check that we can't accidentally assign a temporary location to an ArrayRef.
// (Unfortunately we can't make use of the same thing with constructors.)
//
// Disable this check under MSVC; even MSVC 2015 isn't inconsistent between
// std::is_assignable and actually writing such an assignment.
#if !defined(_MSC_VER)
static_assert(
!std::is_assignable<ArrayRef<int *>, int *>::value,
"Assigning from single prvalue element");
static_assert(
!std::is_assignable<ArrayRef<int *>, int * &&>::value,
"Assigning from single xvalue element");
static_assert(
std::is_assignable<ArrayRef<int *>, int * &>::value,
"Assigning from single lvalue element");
static_assert(
!std::is_assignable<ArrayRef<int *>, std::initializer_list<int *>>::value,
"Assigning from an initializer list");
#endif

namespace {

TEST(ArrayRefTest, AllocatorCopy) {
Expand Down Expand Up @@ -146,6 +166,14 @@ TEST(ArrayRefTest, InitializerList) {
ArgTest12({1, 2});
}

TEST(ArrayRefTest, EmptyInitializerList) {
ArrayRef<int> A = {};
EXPECT_TRUE(A.empty());

A = {};
EXPECT_TRUE(A.empty());
}

// Test that makeArrayRef works on ArrayRef (no-op)
TEST(ArrayRefTest, makeArrayRef) {
static const int A1[] = {1, 2, 3, 4, 5, 6, 7, 8};
Expand Down