M
Mark A. Gibbs
i have a question about class design, specifically regarding accessor
functions. which is probably a better design?
class foo
{
public:
void name(string const& n) { name_ = n; }
string name() const { return name_; }
private:
string name_;
};
class foo
{
public:
string& name() { return name_; }
string name() const { return name_; }
private:
string name_;
};
the difference from the client point of view is how you set the name:
foo f;
f.name("name");
// or
f.name() = "name";
the way i figure it, the first would make assignments explicit, and
prevent accidental assignments. however, when you consider *reading* the
name, you get a different story. there's no difference for simple types
(with fast copying/copy construction), but for expensive types you pay
for a copy construction (or at least something to that effect) using the
first option, even if you don't need it. with the second you only pay
for it on const objects (and i'll get to that next).
now, for integral types, it's not a cost issue, so there it's just a
style issue. but for code passing bigger things around, there is no
point paying for unnecessary copying if it can be avoided. given that
constraint, this would seem like the best option:
class foo
{
public:
string& name() { return name_; }
string const& name() const { return name_; }
private:
string name_;
};
are there any thoughts on this?
mark
functions. which is probably a better design?
class foo
{
public:
void name(string const& n) { name_ = n; }
string name() const { return name_; }
private:
string name_;
};
class foo
{
public:
string& name() { return name_; }
string name() const { return name_; }
private:
string name_;
};
the difference from the client point of view is how you set the name:
foo f;
f.name("name");
// or
f.name() = "name";
the way i figure it, the first would make assignments explicit, and
prevent accidental assignments. however, when you consider *reading* the
name, you get a different story. there's no difference for simple types
(with fast copying/copy construction), but for expensive types you pay
for a copy construction (or at least something to that effect) using the
first option, even if you don't need it. with the second you only pay
for it on const objects (and i'll get to that next).
now, for integral types, it's not a cost issue, so there it's just a
style issue. but for code passing bigger things around, there is no
point paying for unnecessary copying if it can be avoided. given that
constraint, this would seem like the best option:
class foo
{
public:
string& name() { return name_; }
string const& name() const { return name_; }
private:
string name_;
};
are there any thoughts on this?
mark