C++ auto-generated copy constructors with const and non-const refs -
consider following code snippet:
#include <iostream> struct foo { foo() = default; foo(foo &) { std::cout << "foo(foo &)" << std::endl; } }; struct bar { foo m; }; int main() { bar b; bar b2(b); }
if code run, foo(foo &) message written. ok, foo doesn't have foo(const foo &)
constructor, base(base &)
constructor generated base
. now, if add following definition of foo
:
foo(const foo &) { std::cout << "foo(const foo &)" << std::endl; }
the foo(const foo &) message written. ok, foo has copy-constructor const ref parameter, base(const base &) generated compiler. but, if declare foo(const foo &)
explicitly deleted:
foo(const foo&) = delete;
then program won't compile following errors:
prog.cc: in function 'int main()': prog.cc:15:13: error: use of deleted function 'bar::bar(const bar&)' bar b2(b); ^ prog.cc:11:8: note: 'bar::bar(const bar&)' implicitly deleted because default definition ill-formed: struct bar { foo m; }; ^~~ prog.cc:11:8: error: use of deleted function 'foo::foo(const foo&)' prog.cc:8:5: note: declared here foo(const foo&) = delete; ^~~
in first revision of code, if foo(const foo&)
not generated, why don't have error, in third revision? , if it's generated, why isn't called (producing no output message), in second revision?
a copy-constructor implicitly declared , defined if there no user-declared copy-ctor, move-ctor, or move-assignment-operator.
it of form x(const x&)
if virtual bases, direct bases , non-static data members t
declare copy-ctor accepting const t&
.
otherwise of form x(x&)
.
an implicitly declared copy-ctor defaulted, , defaulted copy-ctor deleted if default-definition (member-wise copy) ill-formed.
you got error because sub-objects copy-ctor accepting const& deleted, making containing classes copy-ctor deleted.
Comments
Post a Comment