Reputation: 1265
Suppose I have a class A
, the class is copyable, but it will take a lot to copy it.
Suppose I have a class B
, it can return a const reference of A
.
class B
{
public:
...
const A& obtainA() const
{
return a;
}
private:
A a;
};
When I want to use A from B, I think the best practice is accessed A in B by const reference
B b;
const A& a = b.obtainA(); // do not needs to the heavy copy operation of A, good.
However, I always forget the const reference, my code looks like follow.
B b;
A a = b.obtainA(); // leads to the heavy copy operation of A, not good
It not only leads to the heavy copy operation but also the unsafety.
If the a
call the non-const member function by mistake, it will leads to the member a
in b be changed out of class.
Is there exists any way can help me to return const reference? I want something like, if not returned by reference, the code can not be compiled. Or any other advice is OK.
Thanks for your time.
A
in my application is the shared array
. The data stored in the array is shared, it just something like the std::shared_ptr
, but manage array of object but not single object.
The array is designed can be shared to reduce the copy overhead. The A
is copyable because the array should be copyable.
The array is a widely used class, thus it is often a member of Array's user, that is the B
in this question.
Upvotes: 1
Views: 65
Reputation: 60208
You could make A
non-copyable, and provide a method to do the copy explicitly.
class A {
private:
A(A const &); // expensive copy
public:
A make_copy() { return *this; }
};
The make_copy
method will create the expensive copy, but other code will no be able to make copies implicitly, since the copy-constructor is private.
Upvotes: 2
Reputation: 454
If you do not want an object to be modified, make the object itself constant:
B const b;
A a = b.obtainA(); // nope, not allowed
I personally believe that everything should be constant unless there is a good reason for it not to be.
Upvotes: 1