You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/api/platform/NonCopyable.md
+45-2Lines changed: 45 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,51 @@
1
1
## NonCopyable
2
2
3
-
The NonCopyable class prevents objects of a class from supporting copy operations. You can easily identify it from its class declaration. It creates a compile-time error if you copy the object. Inheriting from this class results in autogeneration of private copy construction and copy assignment operations, which are not accessible in derived classes.
3
+
By default, C++ objects are copyable. Unfortunately some type of objects like resources or polymorphic types are not meant to be copied as they have unique identities.
4
4
5
-
We recommend using the NonCopyable class whenever a class owns a resource (lock/hardware/file) that should not be copied to another class.
5
+
To prevent copy to happen, a common practices has been to declare the copy constructor and copy assignment operator of non copyable types privates. This pattern has the disadvantage of not being semantically explicit. Therefore it can be hard to find out if a type is copyable or not.
6
+
7
+
The `NonCopyable` class is here to solves these issue. Simply inherit privately from it and you're done.
// Copy construction generates a compile time error.
15
+
Resource r3 = r1;
16
+
17
+
// Copy assignment generates a compile time error.
18
+
r1 = r2;
19
+
```
20
+
21
+
The non copyable properties also transfer to classes that derives from a non copyable class as well as classes that owns a non copyable instance:
22
+
23
+
```c++
24
+
class DerivedResouce : public Resource { /* DerivedResource code */ };
25
+
26
+
DerivedResouce r1, r2;
27
+
28
+
// Copy construction generates a compile time error.
29
+
DerivedResouce r3 = r1;
30
+
31
+
// Copy assignment generates a compile time error.
32
+
r1 = r2;
33
+
34
+
class ResourceOwner {
35
+
/* code */
36
+
Resource r;
37
+
};
38
+
39
+
ResourceOwner o1, o2;
40
+
41
+
// Copy construction generates a compile time error.
42
+
ResourceOwner o3 = o1;
43
+
44
+
// Copy assignment generates a compile time error.
45
+
r1 = r2;
46
+
```
47
+
48
+
We recommend inheriting from the `NonCopyable` class whenever a class is a resource or owns a resource (lock/hardware/file) that should or could not be copied.
0 commit comments