Home > OS >  Does calling a member variable of constexpr struct omits a whole constructor evaluation?
Does calling a member variable of constexpr struct omits a whole constructor evaluation?

Time:07-19

Let's say I have the following structure:

struct MyData {
    int minSteps{1};
    int maxSteps{64};
    double volume{0.25/7};
};

constexpr MyData data()
{
    return MyData();
}

Does any of expressions below make an instance of the MyData structure constructed somewhere before the value is assigned?

int steps = data().minSteps;
const int maxSteps = data().maxSteps;
constexpr double volume = data().volume;

CodePudding user response:

It's very unlikely an instance of MyData will actually be created if you compile your code with optimizations on. Any modern compiler should optimize it out. GCC will do so even at O0, MSVC will optimize it out at O1, so it's fair to say you likely don't need to worry about it if you don't intend to compile your code with optimizations completely turned off.

Take a look at it on Compiler Explorer.

  • Related