Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to pass pointers to data members to base class constructor?

Is it safe to pass pointers to data members to base class constructor? i.e., is the memory layout of the derived class data members, at least, already set before the base class constructor is called, even if the data members are not yet initialized?

Obviously, dereferencing the pointers must only be done after construction has completed, and the objects pointed to are already valid. But the question is if it's guaranteed that the pointers received by the base class constructor would actually still point to their objects once construction of the derived object has completed.

The motivation is providing some functionality in the base class, for example iterating over the pointers-to-objects provided at construction and do something for each at a later time.

It's possible to just provide a setter accessible to the derived class, but I'm curious if it's also safe to provide the pointers at construction time.

Example:

#include <iostream>
#include <utility>
#include <vector>

struct Base {
   Base(std::initializer_list<int*> ptrs = {}) : ptrs_(ptrs) {}
   std::vector<int*> ptrs_;
};

struct Derived : public Base {
    Derived() : Base{{&a_,&b_,&c_}} {}
    int a_=1, b_=2, c_=3;
};

int main()
{
    Derived obj;
    for (auto* ptr : obj.ptrs_) { std::cout << *ptr << '\n'; }
}

https://wandbox.org/permlink/rDJw0UU8KcWckLlo

like image 385
Danra Avatar asked Apr 10 '18 15:04

Danra


1 Answers

Your code is fine. But note that the behaviour on dereferencing the pointers in the base class constructor would be undefined.

You are allowed to pass a pointer or reference to a member variable to a base class constructor, but you must not actually access the object in that base class constructor.

like image 178
Bathsheba Avatar answered Sep 19 '22 14:09

Bathsheba