Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

gcc - C++ const question

If I do this:

// In header 
class Foo {
void foo(bar*);
};

// In cpp
void Foo::foo(bar* const pBar) {
//Stuff
}

The compiler does not complain that the signatures for Foo::foo do not match. However if I had:

void foo(const bar*); //In header
void Foo::foo(bar*) {} //In cpp

The code will fail to compile.

What is going on? I'm using gcc 4.1.x

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the first, you've promised the compiler, but not other users of the class that you will not edit the variable.

In your second example, you've promised other users of the class that you will not edit their variable, but failed to uphold that promise.

I should also note that there is a distinct difference between

bar* const variable

and

const bar* variable

and

const bar* const variable

In the first form, the pointer will never change, but you can edit the object that is pointed to. In the second form, you can edit the pointer(point it to another object), but never the variable that it points to. In the final form, you will neither edit the pointer, nor the object it points to. Reference

To add a bit more of a clarification to the question stated, you can always promise MORE const than less. Given a class:

class Foo {
    void func1 (int x);
    void func2 (int *x);
}

You can compile the following implementation:

Foo::func1(const int x) {}
Foo::func2(const int *x) {}

or:

Foo::func1(const int x) {}
Foo::func2(const int* const x) {}

without any problems. You've told your users that you may possibly edit their variables. In your implementation, you've told the compiler that this particular implementation will not edit those variables, even though the told the users you might. You haven't broken a promise to the user, and so the code compiles.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...