C++ Logo

std-discussion

Advanced search

Re: Const

From: Russell Shaw <rjshaw_at_[hidden]>
Date: Fri, 15 Nov 2024 12:03:04 +1100
On 15/11/24 09:52, Thiago Macieira via Std-Discussion wrote:
> On Thursday 14 November 2024 15:40:02 Mountain Standard Time Russell Shaw via
> Std-Discussion wrote:
>> I can define consts without memory locations like:
>>
>> -------------------------------
>> struct S {
>> static const int x = 0;
>> static const int y = 0;
>> static const int z = 0;
>> };
>>
>> int a = S::x;
>> -------------------------------
>
> Incorrect. If you ODR-use the above, your linker will likely fail.

Hi, g++ doesn't complain:

--------------------------------
#include <iostream>

struct S {
      static const int x = 1;
      static const int y = 2;
      static const int z = 3;
};

int a = S::x; // ok

const int *px = &S::x; // undefined reference to `S::x'

int main()
{
     std::cout << "x is " << S::x << std::endl; // ok

     std::cout << "addr of x is " << &S::x << std::endl;
                            // undefined reference to `S::x'
}
--------------------------------

The operator<< function calls can take advantage that a temporary xvalue
can be created for const arguments.

However, is not "int a = S::x;" an odr-use ? I think it is not, after
reading in more detail, i think (5.2) applies:

--------------------------------
5 A variable is named by an expression if the expression is an
id-expression that denotes it. A variable x that is named by a
potentially-evaluated expression E is odr-used by E unless

—(5.1) x is a reference that is usable in constant expressions (7.7), or

—(5.2) x is a variable of non-reference type that is usable in constant
expressions and has no mutable subobjects, and E is an element of the
set of potential results of an expression of non-volatile-qualified
non-class type to which the lvalue-to-rvalue conversion (7.3.2) is
applied, or

—(5.3) x is a variable of non-reference type, and E is an element of the
set of potential results of a discarded-value
expression (7.2.3) to which the lvalue-to-rvalue conversion is not applied.
--------------------------------

Received on 2024-11-15 01:03:09