Posts

Showing posts with the label undefined-behavior

Can a primitive-type data member of a derived class be used as a parameter to its base constructor?

14 2 Inspired by my (currently deleted) answer to this question (but there's a summary in my comment thereto), I was wondering whether the constructor for the Derived class in the code below exhibits undefined behaviour. #include <iostream> class Base { public: Base(int test) { std::cout << "Base constructor, test: " << test << std::endl; } }; class Derived : public Base { private: int variable; public: Derived() : Base(variable = 50) { // Is this undefined behaviour? } }; int main() { Derived derived; return 0; } I know that, when the base c'tor is called, the derived object has not yet (formally) been constructed, so the lifetime of the variable member has not yet started. However, this e...

valgrind shows memory leak in std::make_unique

I'm using valgrind to check for memory leaks. Unfortunately I get a Leak_DefinitelyLost warning. Attached is a simplified version of my code that reproduces the error: #include <iostream> #include <vector> #include <memory> #include <unordered_map> using namespace std; class Base{ public: explicit Base(double a){ a_ = a; } virtual void fun() = 0; protected: double a_; }; class Derived_A : public Base{ public: Derived_A(double a, vector<double> b, vector<double> c): Base(a), b_{b}, c_{c}{ } void fun() override{ cout << "Derived_A " << a_ << endl; } private: vector<double> b_; vector<double> c_; }; class Derived_B : public Base{ public: Derived_B(double a, double b, double c): Base(a), b_{b}, c_{c}{ } void fun() override{ cout << "Derived_B " << a_ << endl; } private: double b_; double c_; }; in...

Is this C++ member initialization behavior well defined?

Let's assume we have a class B that has a member which is default initialized to 42. This class knows how to print the value of its member. (It does so in the c'tor): struct B { B() : member(42) { printMember(); } void printMember() const { std::cout << "value: " << member << std::endl; } int member; }; Then we add a class A which receives a const reference to a B and asks B to print its value: struct A { A(const B& b) { b.printMember(); } }; Finally we add another class Aggregate that aggregates an A and a B. The tricky part is that object a of type A is declared before object b type B, but then a is initialized using a (not yet valid?) reference to b: struct Aggregate { A a; B b; Aggregate() : a(b) { } }; Consider the output of creating an Aggregate (I have added some logging to both c'tor and d'tor of A and B) (Try it online!): a c'tor value: 0 b c'tor value: 42 b d'tor a d'tor Am I right to assume that it...