Reputation: 2009
I am trying to work out how to convert a const struct reference to a non-const struct pointer.
I have a struct called Foo:
struct Foo
{
Foo& someFunc()
{
//do something
return *this;
}
};
I have a method:
struct Bar
{
Foo* fooPointer;
void anotherFunc(const Foo& foo)
{
// set fooPointer to foo's pointer
}
};
I will call it like this:
Foo foo;
Bar bar;
bar.anotherFunc(foo.someFunc());
But how do I write anotherFunc()?
void anotherFunc(const Foo& foo)
{
fooPointer = &foo; // <-- This doesn't work as foo is still const
}
Upvotes: 1
Views: 1718
Reputation: 254691
The best answer is "don't do that, it's crazy". Either change the pointer type to const Foo*
if it won't be used to modify the object, or the reference to Foo&
if it will.
If you genuinely have a good reason to discard const-correctness, then there's a cast for that
fooPointer = const_cast<Foo*>(&foo);
but first consider why you want to do this, and how you can prevent the error of ending up with a non-const pointer to a const object. Or worse, a pointer to a temporary that lingers after its demise.
Upvotes: 6
Reputation: 12907
You could accept it directly as a pointer or non-const reference to Foo
.
The way you're passing your Foo
, you won't be able to do that without a const_cast
, which feels wrong except in a few precise case.
As you're storing it with a pointer to non-const Foo
, you should take the parameter as non-const also. Think about the interface: your struct has a function that takes a Foo
with const qualification, implying "I will only peak at it", but then your function casts it and stores it in a way that allows modification. It's a bit like lying to users of your code (and you are the first user of your code).
Upvotes: 4