4

In [vector.cons] there is the std::vector constructor (emphasis mine):

template<class InputIterator>
  constexpr vector(InputIterator first, InputIterator last,
                   const Allocator& = Allocator());

Effects: Constructs a vector equal to the range [first, last), using the specified allocator.

Complexity: Makes only N calls to the copy constructor of T (where N is the distance between first and last) and no reallocations if iterators first and last are of forward, bidirectional, or random access categories. It makes order N calls to the copy constructor of T and order logN reallocations if they are just input iterators.

However, the following example compiles fine in GCC, Clang (using libc++), and at least in the version of MSVC hosted in godbolt.org.

#include <cstddef>
#include <vector>
#include <complex>

class A
{
private:
  std::complex<double> const x;

public:
  A() = delete;
  A(A const &) = delete;
  explicit A(std::complex<double> const x_) : x(x_) {}
};

void f(std::size_t Size)
{
std::vector<std::complex<double>> v(Size);

std::vector<A> u(std::begin(v), std::end(v));
}

i. e. the appropriate constructor is chosen instead of the deleted copy constructor. Can I rely on such behavior? Am I misunderstanding the standard wording?

Community
  • 1
  • 1
metalfox
  • 6,301
  • 1
  • 21
  • 43
  • Why not `v.begin(), v.end()` ?? – DumbCoder Jan 14 '20 at 11:53
  • @DumbCoder the code above is more generic as it works also for C-style arrays – bartop Jan 14 '20 at 11:54
  • 3
    @DumbCoder, see [this question - "Why use non-member begin and end functions in C++11?"](https://stackoverflow.com/questions/7593086/why-use-non-member-begin-and-end-functions-in-c11). – Evg Jan 14 '20 at 11:54
  • @DumbCoder I tend to use the free functions because they also work e.g. with `std::valarray` and plain arrays. – metalfox Jan 14 '20 at 11:55
  • @bartop I am aware of that but why in this case ? That was my query. – DumbCoder Jan 14 '20 at 11:56
  • 6
    I would say wording issue, as it is not necessary **copy** constructor. – Jarod42 Jan 14 '20 at 11:59
  • 1
    @DumbCoder Because the OP never said from where the pair of iterators shall come from. Because he's talking in the general case (and C-style arrays are in). Because the code shown is just an example and the way to get the iterators is not really the question here... :) – Fareanor Jan 14 '20 at 12:05
  • This is subtly different to the duplicate, as `A` is only *explicitly* convertible from `std::complex` – Caleth Jan 14 '20 at 14:15

0 Answers0