我无法理解将setter函数标记为的目的constexpr,这是自C++ 14以来允许的.我的误解来自下一个情况:我声明了一个带有constexpr c-tor的类,我将在constexpr上下文中使用它,通过创建该类的constexpr实例constexpr Point p1.对象p1现在是常量,其值无法更改,因此constexpr无法调用setter.另一方面,当我class Point在非constexpr上下文中创建my的实例时Point p,我可以为该对象调用setter,但是现在setter不会在编译时执行,因为该对象不是constexpr!
因此,我不明白如何使用constexprsetter 增强代码的性能.
这是演示在非constexpr对象上调用constexpr setter的代码,这意味着运行时计算,而不是编译时:
class Point {
public:
constexpr Point(int a, int b)
: x(a), y(b) {}
constexpr int getX() const noexcept { return x; }
constexpr int getY() const noexcept { return y; }
constexpr void setX(int newX) noexcept { x = newX; }
constexpr void setY(int newY) noexcept { y = newY; }
private:
int x;
int …Run Code Online (Sandbox Code Playgroud)