简体   繁体   中英

Programming principles and practice using C++ error: constexpr

In Stroustrup's "Programming principles and practice" book, there's an example of constexpr like this:

void user(Point p1)
{
    Point p2 {10,10};
    Point p3 = scale(p1); // OK: p3 == {100,8}; run-time evaluation is fine
    constexpr Point p4 = scale(p2); // p4 == {100,8}
    constexpr Point p5 = scale(p1); // error: scale (p1) is not a constant
                                    // expression
    constexpr Point p6 = scale(p2); // p6 == {100,8}
    // . . .
}
  • But think he is mistaken: p2 although initialized with constant expression arguments (literals here 10, 10) it is not a constexpr object because it is not declared so.

So normally p4 and p6 are in error here: (cannot use p2 in a constant expression). it is like p1 .

  • To correct it:

     constexpr Point p2{10, 10};

You know who is really good at telling you if something is allowed as a constexpr ? Your compiler. https://godbolt.org/z/4Kdocx83v

And you are right, it's broken.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM