Reputation: 6464
(Newbie learning c++ with existing codebase) Consider the following snippet:
class Filter
{
...
public:
Filter();
int addFilter(gFilter &filterDesc);
…
};
class gFilter
{
public:
….
inline const RangeOfUInt& getProto() const
{
return proto;
}
private:
…
RangeOfUInt proto;
…
};
typedef struct
{
ValueType type;
uint32_t value1;
uint32_t value2;
} UIntRange;
typedef std::list<UIntRange> RangeOfUInt;
…
const RangeOfUInt protos = filterDesc.getProto(); // XXX
So in this example, getProto() returns const reference and will create a copy for 'protos' ?
Upvotes: 3
Views: 15159
Reputation: 18964
Yes, you are exactly right. protos
is a copy made from the reference returned from getProto
. (The caller creates the copy, getProto
doesn't.)
Upvotes: 2
Reputation: 3336
I think if you want a const reference then keep the method as is change and your call as noted by @jayadev to be const RangeOfUInt& protos = filterDesc.getProto();
If you want to modify a copy, then have a method call that just returns a copy. If you are using c++11 most items ( not sure what ValueType is ) seem move constructable and with copy value optimization you will not lose performance it will get constructed directly into the new object. ( see NVRO )
RangeOfUInt protos = filterDesc.getProto();
class gFilter
{
public:
….
inline RangeOfUInt getProto()
{
return proto;
}
private:
…
RangeOfUInt proto;
…
};
Upvotes: 0
Reputation: 3711
Typically it will create a copy of the protos, 'typically' because compiler might add some optimizations depending on the specific code paths, but while coding we need not worry about that. Since you are looking only for a reference the following change would avoid the copy.
const RangeOfUInt& protos = filterDesc.getProto(); //Make the return variable a reference
Upvotes: 1