How much so? I think I could come up with some ways of making it less efficient? :D so it's a bad idea then? So the way to is to make the getter and calling it in the constructor? Cool, thanks!
Printable View
How much so? I think I could come up with some ways of making it less efficient? :D so it's a bad idea then? So the way to is to make the getter and calling it in the constructor? Cool, thanks!
Because it doesn't make sense to call the copy constructor inside a setter function. You are erasing and re-initializing the values of any other data members in the class. That's not what setter functions typically do. If that really is what you want, normally you would make an operator= that takes the new value, or give the function a different name like ReInitialize or something that makes it clear what is happening.
If you don't mean to re-initialize all the other data members, and you just want to avoid duplicating the code, then follow the advice of others in the thread and just call the setter function from your constructor instead of the other way around. Personally, I would use the initializer list to initialize the value, then have the setter set the value directly, and not worry about code duplication in this particular case (since the code really isn't duplicated).
this might work well in certain situations - a delegated construction idiom:
sample usage:Code:template <class Type>
inline
Type &
construct(Type & obj)
{
return *(new((Type*)&obj)Type());
}
struct constructed
{
template <class Type>
inline
constructed(Type & obj)
{
construct(obj);
}
/* dummy */
inline
constructed(void)
{
}
};
Code:class thingy : public constructed
{
public:
int i, & r, * p;
/* invoked from constructed(*this) */
thingy(void)
: i(1024), p(&i), r(i)
{
}
thingy(int j)
: constructed(*this), i(j), r(i)
{
}
thingy(const thingy & rhs)
: constructed(*this), r(i)
{
*this = rhs;
}
thingy &
operator = (const thingy & rhs)
{
i = rhs.i;
return *this;
}
friend
ostream &
operator << (ostream & os, const thingy & thing)
{
return os << thing.i;
}
};