问题
I have a class Foo
. Foo
has a few non-const methods. I am okay with calling non-const methods on a temporary Foo
object; I am only interested in what the methods actually return, than what they do to the Foo
object itself.
First question: Does this, by itself, necessary indicate that the class Foo
is not well-designed?
Second question: If I want to continue with Foo
as-is, but I still want to be able to pass Foo
objects by reference to functions that will call non-const methods on it, what would be the best way to do it?
This is what I arrived at:
// The function that performs work on a Foo object.
int TakeFoo (Foo& FooBar) { ... }
// An overload just to accept temporary Foo objects.
int TakeFoo (Foo&& FooBar)
{
// Delegate
return TakeFoo(FooBar);
}
The alternative approach is just doing this:
int TakeFoo (const Foo& FooBar)
{
Foo& MyFooBar = const_cast<Foo&>(FooBar);
// Do work on MyFooBar
}
But this approach has the problem that you may be const-cast'ing away the const on an object that was actually declared const, which would put me in undefined-behavior-land.
Edit:
Code examples that use TakeFoo:
Foo GimmeFoo() { ... }
cout << TakeFoo(GimmeFoo()) << endl;
Foo ConstructedFoo(...);
cout << TakeFoo(ConstructedFoo) << endl;
// Continue to use ConstructedFoo
回答1:
Answer to your second question:
If your function TakeFoo is meant to call non const members of Foo then use
int TakeFoo (Foo& FooBar);
If you are sure that TakeFoo only takes an rvalue as argument then use
int TakeFoo (Foo&& FooBar);
If you want to do some changes to Foo in order to compute the int
return value then use
int TakeFoo (const Foo& FooBar)
{
Foo FooBar MyFooBar = FooBar;
// do something with MyFooBar and return int
}
Or
int TakeFoo (Foo FooBar);
Answer to your first question:
int TakeFoo (FooBar)
should not change FooBar in order to compute the int
result.
A better design would be
Foo transform_foo(Foo const& foo);
int compute_result(Foo const& foo);
int TakeFoo(Foo const& FooBar)
{
return compute_result( transform_foo(FooBar) );
}
来源:https://stackoverflow.com/questions/17199695/how-to-override-no-non-const-reference-to-temporary-object-correctly