I have a (virtual) function which returns a std::vector with a single value. Let’s assume the class looks like:
#include <vector>
class Z; // irrelevant
class C
{
Z& something;
public:
typedef std::vector<Z*> list_type;
virtual list_type f();
};
Is it better to use the repetitive constructor:
C::list_type C::f()
{
return list_type(1, &something);
}
or just push_back() the single element:
C::list_type C::f()
{
list_type ret;
ret.push_back(&something);
return ret;
}
If you consider “better” to be “short code”, then probably the repetitive constructor is better because is shorter and therefore more concise.
In terms of functionality, both are equal.
In terms of performance, the repetitive constructor can be better because it can call
reserve()as it knows beforehand the total number of elements that it’s going to allocate. However, you are using it just to create an element, so I guess it does not matter.