Const-Correctness on complex return value
-
22-09-2019 - |
Question
struct Foo { char * DataPtr; };
class ISomeInterface {
public:
Foo GetFoo( ) const;
Foo GetFoo( );
};
The Foo::DataPtr
is a pointer to an internal buffer of the object behing ISomeInterface
. Is there a way to make sure that the Foo::DataPtr
returned by the const version of ISomeInterface::GetFoo
is a const char *
?
Solution
You need a
struct ConstFoo {
const char* DataPtr;
};
for this. The const in C++ is not transitive. (this is also why you have iterator
and const_iterator
.)
OTHER TIPS
A struct
struct Foo {
char * DataPtr;
}
is not the same as
struct Foo {
const char * DataPtr;
}
so you cannot differentiate how you would like.
You could make the const GetFoo()
return a const Foo
object (which I suspect is not what you want, as it will make all the member variables const), or make another struct with a const char * DataPtr
(say FooConst
) which is returned on the const call.
You could try to change the design of your Foo
and 'hide' the acess to DataPtr
behind functions. For instance:
class Foo {
char * DataPtr;
public:
//just some examples
void doThis() const {}
void doThat() {}
};
class ISomeInterface {
public:
const Foo GetFoo( ) const { return Foo(); }
Foo GetFoo( ) { return Foo(); }
};
...
const Foo foo1 = ISomeInterface().GetFoo();
foo1.doThis();
foo1.doThat(); //error
Foo foo2 = ISomeInterface().GetFoo();
foo2.doThis();
foo2.doThat();
Providing functions that define which operations are const and those that are not you can avoid duplicating your Foo
and obtain the const-correctness restrictions you seem to be aiming for.