C++ initializing pointer/reference/copy nuances -
context: embedded programming , initializer list nuances, 1 think should invoke copy constructor.
question: instantiation of class in class's initializer list initialize value-held member variable invoke copy constructor? example provided below testclasscopy has member variable testmember held value opposed pointer or reference. cppreference page not seem cover sufficiently in examples provided.
bonus question: copy constructor invoked in initializer list produce time/space perf impact? seems compiler should able optimize away if c++ spec allows.
here's code (build tested vs2015 toolchain):
testmember.h (not showing testmember.cpp space reasons)
#pragma once #include <stdint.h> class testmember { public: testmember(uint8_t); private: uint8_t m_value; };
testclasscopy.h
#pragma once #include "test_member.h" class testclasscopy { public: testclasscopy(); virtual ~testclasscopy(); private: testmember m_member; };
testclasscopy.cpp
#include "test_class_copy.h" testclasscopy::testclasscopy() : m_member(testmember(255)) { // invokes copy constructor yes? } testclasscopy::~testclasscopy() { }
for completeness, other things might making assumptions shouldn't:
for member pointer testmember, 'new' in initializer list , 'delete' in destructor should sufficient.
for member reference, understanding there's more nuance in if reference passed constructor, can assign (since lifetime managed outside of initializer list). however, if testmember instantiated in initializer list (into reference), that's no-no since testmember temporary goes away after initialization complete.
testmemberreference.h
#pragma once class testmember; class testclassreference { public: testclassreference(); virtual ~testclassreference(); private: testmember& m_member; };
testmemberreference.cpp
#include "test_class_reference.h" #include "test_member.h" testclassreference::testclassreference() : m_member(testmember(255)) { // ew, don't this; testmember temporary go out of scope } testclassreference::~testclassreference() { }
this cppreference page not seem cover sufficiently in examples provided
that cppreference page says "initializes base or member named class-or-identifier using direct initialization" , if click that, can read that, of c++17,
if initializer prvalue expression cv-unqualified type same class t, initializer expression itself, rather temporary materialized it, used initialize destination object: see copy elision
so answer is: in c++17 no copy constructor called. before c++17, copy constructor technically called, copy elision eliminated call. still observe it, proof, compiling example g++ -fno-elide-constructors -o0 -std=c++14
Comments
Post a Comment