C ++具有构造函数的类的向量 [英] C++ vectors of classes with constructors

查看:156
本文介绍了C ++具有构造函数的类的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//Using g++ and ubuntu.
#include <vector>
using namespace std;

定义一个类:

class foo(){
(...)
foo(int arg1, double arg2);
}

构造函数:

foo::foo(int arg1, double arg2){ 
(...) //arrays whose length depend upon arg1 and arg2
} 

我想这样做:

vector<foo> bar(10); //error: no matching function for call to 'foo::foo()'
bar[0] = new foo(123, 4.56);
(...)

另一种方法push_back:

An alternative method (which I like less) is to use push_back:

vector<foo> bar; //works
bar.push_back(new foo(123, 4.56)); //throws similar error.
//Omitting the "new" compiles but throws a "double free or corruption (fasttop)" on runtime.

我想让矢量的不同元素被不同地构造,所以我不想使用重复序列构建子。
应该怎么办?

I want different elements of the vector to be constructed differently, so I don't want to use the "Repetitive sequence constructor". What should be done?

推荐答案

为什么要使用 new 当没有动态内存需要创建?当然,使用 new 将失败,当 push_back foo * c $ c>接受 foo 。 (这是你有一个向量,毕竟)。

Why are you using new when no dynamic memory needs to be created? Of course using new will fail, it results in a foo* when push_back accepts a foo. (That's what you have a vector of, after all.)

push_back 有什么问题?如果你想保留内存,使用 reserve();在向量的构造函数中提供一个数字,使得第二个参数(隐式地 foo()

What's wrong with push_back? If you want to reserve memory up front, use reserve(); providing a number in the constructor of vector makes that many copies of the second parameter (which is implicitly foo(), which won't work hence your errors), which isn't the same as simply reserving memory.

如果做正确的事情(没有 new )崩溃,故障是在你的代码,而不是向量。您可能没有编写管理资源的正确类。*(记住 Big Three ,请使用复制和交换惯用语

If doing things correctly (no new) crashes, the fault is in your code and not vector. You probably haven't written a proper class that manages resources.* (Remember The Big Three, use the copy-and-swap idiom.)

*我说这是因为你说 //长度取决于arg1和arg2的数组
,我怀疑这意味着你在你的类中有 new [] 。没有大三,你的资源管理将失败。

*I say this because you say "//arrays whose length depend upon arg1 and arg2 ", which I suspect means you have new[] in your class somewhere. Without the Big Three, your resource management will fail.

你不应该管理资源,类有一个责任。这意味着它应该是动态数组,或使用动态数组,但不能同时管理和使用动态数组。所以把资源分解成自己的类,然后再使用另一个类(yours)。动态数组是一个 std :: vector ,所以你已经做到了。 任何您需要一个动态数组,使用向量;没有理由不会。

You shouldn't be managing resources anyway, classes have one responsibility. That means it should either be a dynamic array, or use a dynamic array, but not both manage and use a dynamic array. So factor out the resources into their own class, and then make another class (yours) which uses them. A dynamic array is a std::vector, so you are already done with that. Any time you need a dynamic array, use a vector; there is never a reason not to.

这篇关于C ++具有构造函数的类的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆