How to replace "no-const reference to temporary object" correctly

I have a Foo class. Foo has several non-constant methods. I agree with calling non-constant methods in a temporary Foo object; What interests me is only what the methods actually return than what they do with the Foo object itself.

First question: is it necessary in itself so that the Foo class 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-constant methods on it, what would be the best way to do this?

This is what I came to:

 // 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); } 

An alternative approach just does this:

 int TakeFoo (const Foo& FooBar) { Foo& MyFooBar = const_cast<Foo&>(FooBar); // Do work on MyFooBar } 

But this approach has a problem in that you can construct 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 
0
source share
1 answer

Answer the second question:

If your TakeFoo function is intended to call non const members of Foo, use

 int TakeFoo (Foo& FooBar); 

If you are sure that TakeFoo only accepts rvalue as an argument, use

 int TakeFoo (Foo&& FooBar); 

If you want to make some changes to Foo to calculate the return value of int , use

 int TakeFoo (const Foo& FooBar) { Foo FooBar MyFooBar = FooBar; // do something with MyFooBar and return int } 

Or

 int TakeFoo (Foo FooBar); 

Answer your first question:

int TakeFoo (FooBar) should not change FooBar to calculate the result of int . The best 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) ); } 
0
source

Source: https://habr.com/ru/post/1487112/


All Articles