使用参数化构造函数创建 class 的向量

Creating vector of class with parametrized constructor

我正在尝试使用参数化构造函数创建 class 的向量。

#include <iostream>
#include <vector>
using namespace std;

struct foo
{
  foo() {
  cout << "default foo constructor " << endl;
  }  
  
  foo(int i)
  {
      cout << "parameterized foo constructor" << endl;
  }
  ~foo() {
    cout << "~foo destructor" << endl;
  }
};

int main()
{
    std::vector<foo> v(3,1);
}

我原以为会有 3 次调用 parameterized foo constructor 但我得到的输出是

parameterized foo constructor
~foo destructor
~foo destructor
~foo destructor
~foo destructor

这里发生了什么?

如何使用 vector 的构造函数,以便使用参数化构造函数创建 class 的对象?

What is happening here ?

您可以添加一个用户定义的复制构造函数来查看您的代码中发生了什么:

#include <iostream>
#include <vector>

struct foo {
  foo() { std::cout << "default foo constructor\n"; }    
  foo(int i) { std::cout << "parameterized foo constructor\n"; }
  ~foo() { std::cout << "~foo destructor\n"; }
  foo(const foo&) { std::cout << "copy constructor called\n"; }  // <---
};

int main() {
    std::vector<foo> v(3,1);
}

Output:

parameterized foo constructor
copy constructor called
copy constructor called
copy constructor called
~foo destructor
~foo destructor
~foo destructor
~foo destructor

来自您正在调用的 std::vector 构造函数上的 cppreference

Constructs the container with count copies of elements with value value.

所以...

How can I use constructor of vector such that objects of class get created with parametrized constructor?

元素是通过调用复制构造函数创建的。然而,它只被调用一次,然后向量被复制填充。