Restrict class from being moved or copied

How can I prohibit any class from being moved or copied? (std:move(), std::copy())
Just delete the copy ctor, move ctor, copy and move assignment operator.
https://abseil.io/tips/143
Thank you
This code shows the move constructor marked with "=delete", and thus unusable. This will not compile.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class test
{
public:
  int i;

  test(){};
  test(test&&) = delete; // no move constructor
};

#include <vector>
using std::vector;

int main()
{
  test A;
  vector<test> vec(5); // five objects in a vector

  vec.push_back(std::move(A));
}




Similarly for the copy constructor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class test
{
public:
  int i;

  test(){};
  test(const test&) = delete; // no copy constructor
};

#include <vector>
using std::vector;

int main()
{
  test A;

  vector<test> vec(5); // five objects in a vector

  vector<test> copytarget;

  std::copy(vec.begin(), vec.end(), back_inserter(copytarget));
}



You can't stop someone simply writing std::move(someObject) because that's simply the same as static_cast<Object&&>(someObject); however, that doesn't actually do anything, doesn't actually do any moving, so it's harmless.

There are various rules about what constructors get created for free under various conditions and so on, but I think " = delete" is what you need.
Last edited on
Topic archived. No new replies allowed.