* David:
Suppose that I have a class A with a constructor A(B b, C c) and I want
to make a vector of A's. Also, suppose that A's are VERY expensive to
construct, copy, assign.
Then a raw vector is contraindicated.
I also want to have a very many vectors of A's
and cannot afford to store a smart pointer to each A as the type in my
vectors..
Why?
So I want to write something like:
v.push_back(A(b1,c1));
You don't: no matter what you do you will then have construction of the
argument followed by copying of the argument.
and not have a sequence which goes like:
... make space for an A in v at v[i]...
construct A() in v[i]
destruct v[i]
assign A(b1,c1) to v[i]
That is a quality-of-implementation issue. The implementation should
just copy-construct the argument in the new space. However, given your
earlier remarks even that seems to be one copy-operation too much.
Unfortunately, this is the behaviour I am seeing in my compiler. I want:
... make space for an A in v at v[i]...
construct A(b1,c1) in v[i]
Is there any known way to ensure that compilers will give the latter
code?
No, but you can easily do it yourself.
Off the cuff:
class ConstructorArguments { ... };
class A
{
protected:
A( A const& another ) { ... }
A( ConstructorArguments const& a ) { ... };
A& operator=( A const& other ) { ... }
public:
virtual ~A() { ... }
};
class AVec
{
private:
static ConstructorArguments const* theArgs;
class AWrapper: public A
{
public:
AWrapper(): A( *theArgs ) {}
// Required for std::vector usage.
AWrapper( AWrapper const& another ): A( another ) {}
AWrapper& operator=( AWrapper const& other ) { ... }
};
std::vector<AWrapper> myVector;
public:
AVec( size_t aCapacity ) { myVector.reserve( aCapacity ); }
void pushBackNew( ConstructorArguments const& args )
{
if( myVector.size() == myVector.capacity() )
{
throw std::runtime_error( "Ooops, this would copy" );
}
theArgs = &args;
myVector.resize( myVector.size() + 1 );
}
A& operator[]( size_t i ) { return myVector[i]; }
A const& operator[]( size_t i ) const { return myVector[i]; }
};
assuming 'resize' constructs and does not subsequently assign (check it
out).
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?