明智地使用“const”函数声明中的关键字 [英] Wise use of "const" keyword in a function declaration

查看:72
本文介绍了明智地使用“const”函数声明中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何在函数定义中适当地使用const关键字。

例如:



const int * const function_name( const * int point) const ;



const int * const Functiontwo( const int * const &) const ;



请解释上述函数声明的const关键字的每个用法。我掌握了基本的想法,但我想知道如何有效地使用它们为什么这些原因?

I need to know that how does to use "const" keyword within a function definition appropriately.
For an example:

const int * const function_name(const * int point) const;

const int*const Functiontwo(const int*const&)const;

Please explain each uses of const keyword for above function declaration.I grasped the basic idea but I wanted to know how to use them efficiently and why is the reason for those?

推荐答案

const 与值或指针一起使用。



如果是值,故事很简单:你把 const 关键字放在函数参数前面声明或不是指针或引用的本地/全局变量:

const is used either with a value or with a pointer.

In case of a value the story is simple: you put the const keyword in front of a function parameter declaration or a local/global variable that isn't a pointer or reference:
const int j = 5;
void func(const in x)
{
    const float f = 0.5f;
}



我认为在这些情况下 const 的含义是显而易见的。



指针/引用:我只演示了指针, const 对引用的工作方式几乎相同(基本上是指针,但是你可以/必须在声明它们时将它们初始化一次。)

const int * int const * 表示相同:指针引用的 int 值或 int 数组是常量。 int * const 表示指针变量本身是常量但引用的数据不是!您当然可以将这些结合起来: const int * const



现在出现一个特例:const方法:


I think the meaning of const in these cases is obvious.

Pointer/reference: I demonstrate just the pointers, const works the almost the same way for references (that are essentially pointers but you can/must initialize them exactly once when you declare them).
const int* and int const* mean the same: The int value or int array referenced by the pointer is constant. int* const means that the pointer variable itself is constant but the data referenced isn't! You can of course combine these: const int* const.

Now a special case comes: const method:

class C
{
    void Method(int param) const
    {
    }
};



这不是一个特例。方法之后的const与方法的隐藏 this 指针参数一起使用。



所以如果正常非const方法的伪代码如下所示:


This isn't really a special case. The const after the method is used with the hidden this pointer parameter of the method.

So if the "pseudo code" of a normal non-const method looks like this:

class C
{
    void Method(C* const this, int param)
    {
    }
};





然后 const 方法的伪代码如下:



then the "pseudo code" of a const method is the following:

class C
{
    void Method(const C* const this, int param)
    {
    }
};



你根本无法在隐藏前面写const这个指针因此语言强制你在方法header声明后写这个const。



this 指针值本身总是 const 即使在非const方法的情况下,你也无法改变 this 的值。通过创建方法 const ,将引用的实例指针标记为 const 。结果是您不能从 const 方法调用非const实例方法,并且您不能修改实例的成员变量,因为您只有 const C * const this 指针......



明智的使用???如果您不希望某人修改指针引用的值或数据,则将其声明为const。期。如果您知道方法不必修改任何成员变量,并且不必调用其他非const成员,则将该方法声明为const。典型示例:


You simply can't write const there in front of the hidden this pointer so the language forces you to write that const after the method "header" declaration.

The this pointer value itself is always const even in case of non-const methods, you cant change the value of "this". By making a method const you mark the instance referenced by the this pointer as const. The result is that you can not call non-const instance methods from that const method and you can not modify the member variables of the instance because you have only a const C* const this pointer...

Wise use??? If you don't want someone to modify a value or data referenced by a pointer then declare it as const. Period. If you know that a method doesn't have to modify any member variables and it doesn't have to call other non-const members then declare the method as const. Typical example:

class Array
{
public:
....
    size_t GetLength() const
    {
         // GetLength() doesn't modify anything inside the array and doesn't call non-const methods.
    }

    void Clear()
    {
        ...
    }
....
};

void Test(const Array& arr)
{
    // Because GetLength() is a const method you will be able to call that method on
    // a const Array pointer/reference/variable too! For this reason it is a good practice
    // to declare every method as const if it doesn't modify the instance, it enables you
    // to use those methods with const instances!
    arr.GetLength();
    
    // This causes a compile error because you try to call a non-const member on a const array.
    arr.Clear();
}





编辑:避免使用可变关键字这基本上是一个黑客。我看过可能有一个地方使用它是合理的。



avoid the usage of the mutable keyword that is basically a hack. I've seen maybe one place where it's usage was reasonable.


请参考前两个解决方案进行解释。我想补充一下为什么你会或者不应该在特定地方使用const:



A) const int foo(); vs. int foo();

没有意义:foo返回一个可以分配给a的值int类型的变量。您可以将常量(例如5)分配给int变量以及变量,因此返回值类型是否声明为const并不会产生任何差异。



B) const int * foo(); vs. int * foo();

结果指向一个持有int的位置,该位置可能不会(或可能)被修改。其他指针可能指向同一个位置,因此无论您是否被允许修改它都会产生影响。



C) int * const foo(); vs. int * foo();

废话的原因与给出的相同如果是A)。第一种形式的结果类型是const指针,但可以分配给非常量指针类型的变量:
Please refer to the first two solutions for explanation. I would like to add to these why you would or should not use const in particular places:

A) const int foo(); vs. int foo();
Doesnt't make sense: foo returns a value which can be assigned to a variable of type int. You can assign constants (such as 5) to an int variable as well as variables, so whether the return value type is declared const or not does not make a difference at all.

B) const int* foo(); vs. int* foo();
The result points to a location holding an int that may not (or may) be modified. Other pointers may be pointing to that same location, so it does make a difference whether you are allowed to modify it or not.

C) int* const foo(); vs. int* foo();
Nonsense for the same reasons as given in case A). The result type of the first form is a const pointer, but may be a assigned to a variable of type non-const pointer:
int* const foo();
int* p = foo(); // valid assignment!

因此第二种形式是等效的(并且误导性较小) )。



D) int foo(const int);

类似在A)和C)中给出的原因,没有必要提供const限定符。它所做的就是阻止foo的实现将参数用作变量。但它并不妨碍实现将该参数复制到非const变量中。



E) int foo(const int *);

见B):foo的实现可能会读取指向的值,但不能修改它。



F) int foo(int * const);

见D):不是特别有用。



G) int foo(int * const&);

见F:没用,也非常混乱:& 表示参数通过引用传递 - 通常用于传递复合变量(如结构),或确保参数可以修改并且可以看到修改由调用者(即该参数用于保存输出值)。由于变量既是const,又不是复合,这根本没有意义。 (它仍然是合法的C ++)



H) int foo()const;

只对类函数合法,它表示不会通过调用此函数来修改此类的实例。





简而言之,在您提供的示例中,只有三个 const 的展示位置非常合理,在案例B),E)和H)中概述。 const 的其他用途虽然合法,但没用。在这些情况下,你最好不要使用 const

The second form is therefore equivalent (and less misleading).

D) int foo(const int);
For similar reasons as given in A) and C), there is no point for providing that const qualifier. All it does is prevent the implementation of foo to use the parameter as a variable. It does not prevent the implementation from copying that parameter into a non-const variable though.

E) int foo(const int*);
See B): the implementation of foo may read the value pointed to, but not modify it.

F) int foo(int* const);
See D): not particularly useful.

G) int foo(int* const&);
See F: not useful and also extremely confusing: the & means the parameter is passed by reference - something normally used to either pass a compound variable such as a struct, or to ensure the parameter may be modified and the modification will be seen by the caller (i. e. the parameter is used to hold an output value). Since the variable is both const, and not a compound, this doesn't make sense at all. (it is still 'legal' C++)

H) int foo() const;
Only legal for class functions, where it indicates that an instance of this class will not be modified by calling this function on it.


In short, in the examples provided by you, only three of the placements of const are really sensible, outlined in cases B), E) and H). The other uses of const, while legal, are not useful. You're better of not using const in these cases.


一个简单的诀窍就是



A simple trick to understand is

const char *ptr = &someVariable;



请参阅* ptr,正常用法表示数据。所以数据是不变的。即你有一个指向常量数据的指针。你不能做像


see *ptr, which as normal usage signifies data. So data is constant. i.e you have a pointer pointing to a constant data. You cannot do something like

char var = 'a';
const char *ptr = &var;

*ptr='c';//not allowed
*ptr++;//not allowed

//but you could do
var = 'x';//or
ptr = &someOtherVariable;





现在其次



now secondly

char* const ptr = &var;
//see the const is after the * signifying that your pointer is constant. Meaning it will point to one location only.

ptr= &someOtherVariable; //not allowed
ptr++; //not allowed

//but the following is allowed
*ptr= 'x';
*ptr++; 





所以对于一个真正恒定的指针,我指的是它指向一个固定的位置,并且该位置的值不能是更改只能通过以下方式实现:



so for a pointer to be truely constant, by which I mean it points to a fixed location and the value at that location cannot be changed can only be achieved by doing this :

const char* const ptr; //constant pointer to a constant value





使用const如下所示



as for use of const as below

int function(const SomeClass& abc) const;



表示我们有一个函数,它将SomeClass作为const引用。函数末尾的const表示该函数不会改变任何数据成员(除非你有一个可变数据成员)。


means we have a function that takes SomeClass as a const reference. And the const at the end of the function signifies that the function does not mutate any data members (unless you have a mutable data member).


这篇关于明智地使用“const”函数声明中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆