Use =delete to state that a function or class member is intentionally unavailable. Calls to deleted members become clear compile-time errors instead of obscure link-time failures. section 2.4 section 9.2
Preventing accidental copying
A unique ArtPiece can forbid both copy construction and copy assignment with `ArtPiece(const ArtPiece&) = delete;` and `ArtPiece& operator=(const ArtPiece&) = delete;`. Attempts such as `ArtPiece dup(ml);` or `ts = ml;` are diagnosed by the compiler. section 9.2
Listing 2.8 A simple class with defaulted and deleted members
class Container {
private:
std::vector<int> values;
public:
Container() = default; #1
Container(const Container& o) : values(o.values) {}
Container& operator=(const Container& o) = delete; #2
void add(int n) { values.push_back(n); }
};
int main() {
Container c1;
c1.add(42);
Container c2(c1);
// c2 = c1; #3
return 0;
}
Compare a Container with a defaulted constructor, a custom copy constructor, and a deleted assignment operator. section 2.4
Listing 9.6 Preventing duplication using delete=
class ArtPiece {
private:
int id;
std::string description;
public:
ArtPiece(int id, std::string d) : id(id), description(d) {}
ArtPiece(const ArtPiece&) = delete;
ArtPiece& operator=(const ArtPiece&) = delete;
const std::string& getDesc() const { return description; }
//void badMethod() { ArtPiece a = *this; }
};
int main() {
ArtPiece ml(333, "Mona Lisa");
ArtPiece ts(444, "The Scream");
// ArtPiece dup(ml); #1
// ts = ml; #2
std::cout << ml.getDesc() << '\n';
// ts.badMethod(); #3
return 0;
}
Inspect a complete noncopyable ArtPiece and the commented operations that now produce compile-time errors. section 9.2
