A class owns an object of type U
. Through a method it exposes this object as a const U&
using a getter (not cheaply copyable, modification is not desired).
A client, now, wants to make use of this API. He wishes to use the instance of U
as part of a complex object (which has no interest in changing the API object).
Therefore, he has at least the following option:
Create a class T
with const U&
as parameter and a private field of type const U&
, where the constructor stores the instance of the API.
This has the extreme disadvantage of making the instances of the class extremely unflexible (e.g. no management using std::vectors), which is not desired.
Not a long time ago, I found that one also could use a std::reference_wrapper<const U>
, to store the const U&
, which would not impose those disadvantages on instances of type T
.
The question now is, does this behave like it is expected and is it a good practice to do so?
In the following and here, you can find a working code using this strategy and the types described.
#include <iostream>
#include <memory>
class U{
public:
uint value;
};
class T{
private:
std::reference_wrapper<const U> _u;
public:
T(const U& u)
:_u(u) {}
const U& GetU(){
return _u;
}
};
const U& provideValue(U& u){
return u;
}
int main()
{
U internalApiValue;
internalApiValue.value = 5;
auto apiValue = provideValue(internalApiValue);
T container(apiValue);
std::cout << container.GetU().value;
}
I guess if this is not a good idea, the only alternative would be avoiding const, because else I would impose high restrictions on the users of such methods (methods exposing const U&
instead of U&
or U
)?