C ++ std :: vector在构造函数中 [英] C++ std::vector in constructor

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

问题描述

我试图编写一个有效的实现下面的复合类:

I am trying to code an effective implementation of the following composite class:

class composite{
  vector<base_class *> Vec;
  //Other useful constants
public:
  composite(vector<base_class*>);
  //Other useful operations...
};

我的问题是关于类的构造函数和实例化,特别是对象Vec。在分钟,我使用下面概述的相当粗略的实现。我的实现要有记忆效率。我几乎是一个新的C ++,所以我不知道我有最佳的解决方案在这里...

My question is about the constructor and instantiation of the class and in particular the object Vec. At the minute, I use the rather crude implementation outlined below. I the implementation to be memory efficient. I'm pretty much a newb with C++, so I'm not sure I have the optimal solution here...

我使用多态性存储不同的派生类在向量,例如

I use polymorphism to store different derived classes in a vector, e.g.

vector<base_class *> Vec1;
Vec1.reserve(2);
class1 * C1 = new class1(....);
Vec1.push_back(C1);
class2 * C2 = new class(....);
Vec1.push_back(C2);

其中class1和class2是base_class的派生类。然后我将Vec1传递给复合的构造函数,如下所示:

where class1 and class2 are derived classes of base_class. I then pass Vec1 to the constructor of composite as follows:

composite::composite(vector<base_class*> Vec1){
   Vec.reserve(Vec1.size());
   Vec.swap(Vec1);
   //etc...
}

我的感觉是在内存上相当有效,因为Vec1在构建之后将是空的(它的元素已经被交换为Vec)。另一方面,它似乎是相当浪费,因为我基本上是将Vec1复制到Vec。有没有更好的方法,我做这个?我可以以某种方式嵌入矢量Vec1到复合?提前感谢!

My feeling is that this is quite efficient on the memory, because Vec1 will be empty after the construction (it's elements have been swapped into Vec). On the other hand, it seems to be quite wasteful, as I am essentially copying the Vec1 into Vec. Is there a better way for me to do this? Can I somehow embed the vector Vec1 into composite? Thanks in advance!

推荐答案

首先,使用正确的智能指针代替原始指针。

First, use proper smart pointer instead of raw pointer.

接下来,在您使用的方法中, reserve()调用完全不必要 - swap()刚刚交换内部指针。

Next - in the method you used, the reserve() call is totally unnecessary - swap() just swaps internal pointers.

最后 - 自从我们在2013年,C ++ 11已经被使用,所以构造函数应该看起来像这样: / p>

And last - since we're in 2013, C++11 is already to be used, so the constructor should look like this:

composite::composite(std::vector<std::unique_ptr<base_class>> v) 
    : vec{ std::move(v) }
{
}

办法?以参数值的值已经复制它,并且由于您不再使用该副本,因此可以安全地移出,从而实现最小量的副本以初始化成员。

Why this way? Taking the parameter by value already copies it, and since you aren't going to use that copy anymore, it is safe to be moved out, which achieves the least amount of copies to initialize the member.

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

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