问题描述
我不明白将setter函数标记为 constexpr
的目的,自C ++ 14开始就允许这样做。
我的误解来自于下一种情况:
我声明了一个带有constexpr c-tor的类,并且通过在该类中创建一个constexpr实例,我将在constexpr上下文中使用它 constexpr点p1
。对象 p1
现在是常量,并且其值无法更改,因此无法调用 constexpr
设置器。
另一方面,当我在非constexpr上下文 Point p $ c $中创建我的
类Point
的实例时c>,我可以调用该对象的setter,但是现在setter将不会在编译时执行,因为该对象不是constexpr!
I cannot understand the purpose of marking the setter function as constexpr
, that is allowed since C++14.My misunderstanding comes from the next situation: I declare a class with a constexpr c-tor, and I am about to use it in a constexpr context, by creating a constexpr instance of that class constexpr Point p1
. An object p1
now is constant and its value could not be changed, so the constexpr
setter could not be called. On the other hand, when I create an instance of my class Point
in a non-constexpr context Point p
, I can call the setter for that object, but now setter will not execute at compile-time, because the object is not constexpr!
结果,我不了解如何使用 constexpr
来使用设置器来增强代码的性能。
As a result, I do not understand how can I enhance the performance of my code using constexpr
for setters.
这是演示了在非constexpr对象上调用constexpr setter,这意味着运行时计算,而不是编译时:
This is the code that demonstrates calling a constexpr setter on an non-constexpr object, that means run-time computation, instead of the compile-time:
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 y;
};
int main() {
Point p{4, 2};
constexpr Point p1{4, 2};
p.setX(2);
}
有人可以帮助我了解将setter函数标记为 constexpr
?
Could anyone help me to understand what is the purpose of marking the setter function as constexpr
?
推荐答案
基本上,当您需要处理时
Basically it is nice when you have to deal with constexpr function.
struct Object {
constexpr void set(int n);
int m_n = 0;
};
constexpr Object function() {
Object a;
a.set(5);
return a;
}
constexpr Object a = function();
这个想法是为了能够执行编译时间在将在编译时执行的另一个函数中进行初始化。不能将其应用于 constexpr
对象。
The idea is to be able to perform compile time initialization within another functions that will be executed at the compile time. It is not done to be applied on constexpr
object.
要知道的另一件事是 constexpr 成员函数就不是 const
成员函数。
Another things to know is that constexpr
member functions are not const
member functions since C++14 :).
这篇关于将设置函数(设置器)标记为constexpr的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!