The struct
struct Vanish
{
int iCount;
int iRow;
};
I defined a std::vector
of Vanish
as a member of my class, and want to initialise it in the constructor like this:
class BigClass
{
public:
BigClass();
private:
std::vector<Vanish> tovanish;
};
void BigClass::BigClass()
{
Vanish empty = {0,0};
tovanish.assign(MAX_VANISH, empty);
}
Is there a better way, or is this considered OK?
Is there a better way?
Yes, sure,
BigClass::BigClass() : tovanish(MAX_VANISH) {}
This gives you a vector with MAX_VANISH
value-initialized Vanish
elements.
It is better to do that in the constructor's initializer list:
BigClass::BigClass()
: tovanish(MAX_VANISH)
{
}
That way, you'll avoid possible vector reallocations. Note that you vector's constructor will value-initialize its elements. Value-initialization of the int
members in Vanish
just zeroes them.
Note that in C++11, using uniform-initialization you could specify other values easily:
BigClass::BigClass()
: tovanish(MAX_VANISH, {42, 24})
{
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.