Consider the following code:
#include <vector>
class A
{
public:
A(A&&); // somewhat expensive
static std::vector<A> make_As()
{
std::vector<A> result;
result.push_back(A(3));
result.push_back(A(4));
return result;
}
private:
A(int); // private constructor
};
Since A
's move constructor is somewhat expensive (for whatever reason), I'd like to avoid calling it and use emplace_back()
instead:
#include <vector>
class A
{
public:
A(A&&); // somewhat expensive
static std::vector<A> make_As()
{
std::vector<A> result;
result.emplace_back(3);
result.emplace_back(4);
return result;
}
private:
A(int); // private constructor
};
Unfortunately, with emplace_back()
, the actual constructor call is done by something in the standard library, which is not privileged enough to be able to call A
's private constructor.
I realize that there's probably little that can be done about this, but nonetheless I feel that since the calls to emplace_back()
occur within a member of A
, they ought to be able to call the private constructor.
Are there any workarounds for this?
The only thing I can think of is to add a friend-declaration to A
, but the precise class that needs to be A
's friend (that is, the class that actually tries to invoke the constructor) is implementation-specific (for example, for GCC it's __gnu_cxx::new_allocator<A>
). EDIT: just realized that such a friend declaration will allow anyone to emplace_back()
A
's constructed with the private constructor into a container of A
's, so it wouldn't really solve anything, I might as well make the constructor public at that point...
UPDATE: I should add that A
's move constructor being expensive is not the only reason to avoid having to call it. It may be that A
is not movable at all (nor copyable). That would not work with vector
, of course, (because emplace_back()
may have to reallocate the vector), but it would with deque
, which also has a similar emplace_back()
method but does not have to reallocate anything.