I ran today against a quite subtle issue I'd like to have your opinion on.
Consider the following garden-variety shared-body-idiom class:
struct S
{
S() : p_impl(new impl) {}
private:
struct impl;
boost::shared_ptr<impl> p_impl;
};
The fun appears when you try to put those into vectors in the following way:
std::vector<S> v(42);
Now, with MSVC 8 at least, all the elements in v
share the same impl
member. Actually, what causes this is the vector
constructor:
template <typename T, typename A = ...>
class vector
{
vector(size_t n, const T& x = T(), const A& a = A());
...
};
Under the scenes, only one S
object gets default constructed, the n
elements of the vector
are copied from it.
Now, with C++11, there are rvalue references. So it cannot work like this. If a vector
is constructed as
std::vector<S> v(42);
then most likely, implementations will chose to default construct the n
objects inside the vector, since copy construction may not be available. This would be a breaking change in this case.
My question is:
- Does the C++03 standard mandates that
std::vector
must have a constructor defined as above, ie. with a default argument ? In particular is there a guarantee that the entries of the vector object get copied instead of default constructed ?
- What does the C++11 standard say about this same point ?
- I see this as a possibility for a breaking change between C++03 and C+11. Has this issue been investigated ? Solved ?
PS: Please no comments about the default constructor of the class S
above. It was this or implementing some form of lazy construction.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…