If you define (or only declare) it yourself, then the compiler will not define it for you.
struct A
{
A (); /*declaration is enough to prevent the compiler from
generating default constructor!*/
};
While the declaration is enough to prevent the compiler from generating default constructor, it is necessary to define it if your code requires the default constructor, otherwise you'll get linker error.
In C++11 (the new ISO Standard), you can disable constructors, copy-constructor, and copy-assignment as:
struct A
{
A(const A&) = delete; //disable copy-constructor
A& operator=(const A&) = delete; //disable copy-assignment
};
Now the interesting part
You can also selectively disable constructor(s) for selected types which makes delete
more interesting. Consider this,
struct A
{
A (int) {}
};
Object of this class can be created not only with int
argument, but any type which implicitly converts to int
. For example,
A a1(10); //ok
A a2('x'); //ok - char can convert to int implicitly
B b;
A a3(b); //ok - assume b provides user-defined conversion to int
Now suppose, for whatever reason, I don't want the users of class A
to create objects with char
or class B
, which fortunately or unfortunately can implicitly convert to int
, then you can disable them as:
struct A
{
A(int) {}
A(char) = delete; //disable
A(const B&) = delete; //disable
};
Now here you go:
A a1(10); //ok
A a2('x'); //error
B b;
A a3(b); //error - assume (even if) b provides user-defined conversion to int
Online Demo : http://ideone.com/ZVyK7
The error messages are very clear:
prog.cpp:9:5: error: deleted function 'A::A(char)'
prog.cpp:10:5: error: deleted function 'A::A(const B&)'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…