我正在阅读 Marshall Cline 的 C++ 常见问题解答。
目前正在研究第 10.5 点中的代码。
我有这个:
class Fred
{
public:
Fred();
Fred(int x, int y)
{
std::cout << "Fred with two ints\n" << std::endl;
};
};
int main()
{
std::vector<Fred>(3, Fred(4,5));
return 0;
}
我希望看到“Fred with two ints”打印 3 次 - 但它只打印了一次。 这是为什么 - 它没有被调用 3 次吗?
最佳答案
这是 vector
的签名您正在调用的构造函数:
vector( size_type _Count, const Type& _Val, const Allocator& _Alloc = Allocator() );
Fred(4,5)
调用您定义的构造函数一次,创建的实例通过引用传递给 vector<Fred>
构造函数。然后,它 [创建的实例] 被复制 3 次到 vector 。复制操作是通过使用(默认)复制构造函数执行的;所以你的构造函数不会被多次调用。
关于c++ - 为什么不多次调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12018180/