c++ - Default constructor is getting called on a const reference member despite non default constructor arguments -
here basic c++ outline of code:
#include <cstdlib> #include <iostream> #include <thread> using namespace std; class m { public: m() = default; ~m() { cout << "called ~m" << endl; } }; class { public: a(int z) : _z(z) { cout << "called a(int z)" << endl; this_thread::sleep_for(chrono::milliseconds(1000)); } a() { cout << "called a()" << endl; this_thread::sleep_for(chrono::milliseconds(1000)); } a(const a& a) { cout << "called a(const a& a)" << endl; _z = a._z; } a(const a&& a) { cout << "called a(const a&& a)" << endl; _z = a._z; } a& operator=(const a& a) { cout << "called a& operator=(const a& a)" << endl; if (&a != this) { cout << "executed a& operator=(const a& a)" << endl; } } virtual ~a() { cout << "called ~a" << endl; } int poll() const { return _z; } private: m _m; int _z = 300; }; class b : public { public: // _a(10) b() : _a(std::move(a(10))) { cout << "called b()" << endl; } virtual ~b() { cout << "called ~b" << endl; } private: const a& _a; }; int main(int argc, char** argv) { b b; a* aptr = &b; a& aref = (*aptr); cout << aref.poll() << endl; return 0; }
from setup above following output:
called a() called a(int z) called ~a called ~m called b() 300 called ~b called ~a called ~m
my issue first line of output (all others make sense given first). initializing member _a
in b() : _a(std::move(a(10)))
, forced _a
const reference member. , ctor int argument gets called well, why default ctor called on a? why no move ctor? therefore temporary object seems constructed , destroyed, no real move happening (as can seen 300 output later on).
now issue not seem related move per se behaviour around const reference member. because if change initialization list to: b(): _a(10)
same issue: somehow default object assigned const reference member , arguments in initialization list ignored. b(): _a(10)
get:
called a() called a(int z) called b() 300 called ~b called ~a called ~m
basically why first line default constructor? , how alter code 10 initialization appears instead of 300 default?
each object of type b has two subobjects of type a. 1 base-class subobject, , other _a
member subobject. call constructor member, base-class subobject default-initialized since haven't explicitly called constructor in initialization list.
you by, example, following:
b() : a(arguments) //<--initialize base-class subobject , _a(std::move(a(10))) { cout << "called b()" << endl; }
Comments
Post a Comment