constexpr references and constant expressions

I

Inconnu

Is the following a valid code?

constexpr const A &ri = 3;
constexpr const int *pi = &ri;

------------------------------------
Code may be more complicated:

struct A
{
int i;
const int &ri;
};

constexpr const A &ra = {1, 3};
constexpr const int *pi = &ra.ri;
--------------------------------------

and even:

struct A
{
int i;
const int &ri;
};

struct B
{
int i;
const A &ra;
};

constexpr const A &rb = {1, {1, 3}};
constexpr const int *pi = &rb.ra.ri;
 
N

Noah Roberts

Is the following a valid code?

constexpr const A &ri = 3;
constexpr const int *pi = &ri;

------------------------------------
Code may be more complicated:

struct A
{
    int i;
    const int &ri;

};

constexpr const A &ra = {1, 3};
constexpr const int *pi = &ra.ri;
--------------------------------------

and even:

struct A
{
    int i;
    const int &ri;

};

struct B
{
    int i;
    const A &ra;

};

constexpr const A &rb = {1, {1, 3}};
constexpr const int *pi = &rb.ra.ri;

I don't have the standard, haven't made use of constexpr, so I could
be quite wrong....but I don't think so. It wouldn't make sense to
me. A constant expression in C++ is an expression that can be
evaluated at compile time. The 'constexpr' statement is meant to
create named constant expressions with variable and function syntax.
What you're doing above though is trying to create a runtime
reference. Just because that reference is constant (and they all are
really) doesn't mean it's a compile-time entity.

I do know that a constexpr is not allowed to make use of anything but
constant expressions. If references aren't allowed, and I seriously
doubt they are, then you can't make a constexpr of a type that
contains one.

Of course, you could always try it with various compilers to get a
rough idea of whether it's allowed or not. Not definitive, but it is
practical.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top