LordAro
LordAro

Reputation: 1289

Ensure move in std vector with trivial type

Say I have a vector of ints

std::vector<int16_t> samples;

Is there a nice way to disable copying into this vector so that only moving is allowed? I know about std::move, but I'd like something like a compile error (like unique_ptr) if copying is attempted, rather than just relying on the programmer to "do the right thing"(tm)

Upvotes: 0

Views: 272

Answers (2)

Drax
Drax

Reputation: 13288

Make an uncopyable wrapper:

#include <vector>

template<typename T>
class   uncopyable
{
public:
  uncopyable(const uncopyable&) = delete;

  uncopyable(uncopyable&&) = default;

  uncopyable(T&& data)
    :
    data_(std::move(data))
  {
  }

public:
  uncopyable&   operator=(const uncopyable&) = delete;

  uncopyable&   operator=(uncopyable&&) = default;

  uncopyable&   operator=(T&& data)
  {
    data_ = std::move(data);
    return *this;
  }

private:
  T       data_;
};

int     main()
{
  std::vector<int>      big(10000);

  uncopyable<std::vector<int>>  uncopyable_big(std::move(big));

  std::vector<int>      other_big(10000);

  uncopyable_big = std::move(other_big);
}

And use this type instead of your vectorif you want to guarantee no copies are made.

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254501

If it's a class member, then just make it private and only allow access in the ways you want:

std::vector<int16_t> const & get_samples() {return samples;}
void set_samples(std::vector<int16_t> && s) {samples = std::move(s);}

Otherwise, there's not much you can do to enforce particular access patterns.

Upvotes: 1

Related Questions