Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'constexpr' non-static member function will not be implicitly 'const' in C++1y; add 'const' to avoid a change in behavior

clang++ give the following warning(see code below):

'constexpr' non-static member function will not be implicitly 'const' in C++1y; add 'const' to avoid a change in behavior

Where should the const be add so? const constexpr size_t getSize() { give another warning:

'const' type qualifier on return type has no effect

code:

constexpr size_t getSize()
{
    return sizeof(header);
}
like image 907
Jack Avatar asked Apr 17 '14 04:04

Jack


People also ask

Is constexpr implicitly static?

constexpr functions are implicitly inline , but not implicitly static .

Is constexpr always const?

A constexpr variable must be initialized at compile time. All constexpr variables are const . A variable can be declared with constexpr , when it has a literal type and is initialized. If the initialization is performed by a constructor, the constructor must be declared as constexpr .

Can a member function be constexpr?

const can only be used with non-static member functions whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types.

What is constexpr function in C++?

constexpr stands for constant expression and is used to specify that a variable or function can be used in a constant expression, an expression that can be evaluated at compile time. The key point of constexpr is that it can be executed at compile time.


2 Answers

I believe it's telling you that the member function can't be called on a const object as of C++1y.

Add const after getSize() to make it a const member function:

constexpr size_t getsize() const { ... }
like image 195
happydave Avatar answered Nov 09 '22 15:11

happydave


Complete testcase:

struct S {
  constexpr int getSize();
};

Diagnostic:

tmp.cc:2:17: warning: 'constexpr' non-static member function will not be
        implicitly 'const' in C++1y; add 'const' to avoid a change in
        behavior [-Wconstexpr-not-const]
  constexpr int getSize();
                ^
                          const

Note in particular the bottom line of the output. That's called a 'fix-it hint' and shows you the text you need to insert (and where to insert it) to fix the problem.

(In this case, the text starts with a leading space, making it slightly less clear that it should be inserted before the semicolon, not afterwards.)

like image 20
Richard Smith Avatar answered Nov 09 '22 14:11

Richard Smith