Skip to content

Commit 52494c4

Browse files
committed
Rework NonCopyable documentation.
1 parent f0ba6cd commit 52494c4

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

docs/api/platform/NonCopyable.md

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,51 @@
11
## NonCopyable
22

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.
44

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.
8+
9+
```c++
10+
class Resource : NonCopyable<Resource> { /* resource code */ };
11+
12+
Resource r1, r2;
13+
14+
// 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.
649

750
### NonCopyable class reference
851

0 commit comments

Comments
 (0)