Suppose you have a class with a member variable declared constant.
class Test
{
public:
Test(const int const_param) : const_member_(const_param) {}
private:
const int const_member_;
};
We want a function that will return an instance of this object either as a “return value”
Test Foo();
Test* Foo();
Test& Foo();
or as an “output parameter” (i.e. a pointer that is passed in).
void Foo(Test* test);
void Foo(Test** test); // maybe this is more correct?
Note this function is the only thing that can create the object (in the above example, Foo will be the only thing that knows the value of const_param and can thus create a Test object)
What would be the best way to do something like this? Is this even possible?
You can just return such an object by copy, unless you have good reason do avoid this design:
If you’d rather handle the object by pointer, use
std::shared_ptr<Foo>instead:Or, if you just need one handler object, use
std::unique_ptr<Foo>.A bit of explanation: Having a constant member in your object essentially means that the object itself has the semantics of a constant object. It is OK to copy constants, but not to reassign them, so in your typical use case you would only create an object of this class once and not reassign it. A copy constructor is automatically defined for you, so you can go straight ahead and say:
Clearly you cannot and would not say
x = make_foo();, because yourxis semantically a constant thing for which reassignment doesn’t make sense.