std :: vector of objects / pointers / smart pointers to pass objects(buss error:10)? [英] std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?

查看:150
本文介绍了std :: vector of objects / pointers / smart pointers to pass objects(buss error:10)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一般建议。下面的代码完全编译并粗略地表示我处理的代码的结构。
简而言之,我想传递一系列从基类(Class1)派生的对象和一些其他参数从一个地方到另一个地方。更确切地说,实现父类的不同子类,收集它们的实例,并通过参数处理。

I would like to ask a general advise. The code below fully compiles and roughly represents the structure of the code i deal with. In a nutshell i want to pass a series of objects derived from the based class (Class1) and some other parameters from one place to another. More precisely, implement different child classes of the parent class, gather instances of those and pass for processing with parameters.

问题是,对象向量或指针向量?我不介意从 C ++ 11 std :: unique_ptr std :: shared_ptr )如果这是更好/更安全/更少的内存泄漏/ etc 由于某种原因。我真的很感激,如果有人可以争论性地建议在容器这种情况和/或提供使用 C ++ 11 的例子。

The question is, would you recommend to use a vector of objects or vector of pointers? I don't mind going for some new stuff from C++11 (std::unique_ptr, std::shared_ptr) if this is better/safer/less memory leaks/etc for some reason. I would really appreciate if someone could arguably advise on container for such a case and/or provide an example using C++11.

p / s / 这里 UncleBens说,如果/当抛出异常时,使用指针可能导致内存泄漏。所以也许我应该使用智能指针任务?

p/s/ here UncleBens said that using pointers could lead to memory leaks if/when exceptions are thrown. So maybe i should really use smart pointers for the task? How would this look?

p / p / s /有趣的,现实生活中的例子给我总线错误:10 使用来自 std :: vector< code>的 Class2 容器< d> *> / std :: vector<容器< d>> 。但是,我不能在一个简单的情况下重现错误...

p/p/s/ funny enough, the real life example gives me Bus error: 10 when i try to use those Class2 objects from std::vector< Container<d>*> / std::vector< Container<d>> . However, i'm not able to reproduce the error in a simple case...

#include <string>
#include <iostream>
#include <vector>


template<int dim>
class Class1 {
   public:

     Class1() {};
    ~Class1() {}; 

};

template<int dim>
class Class2 : public Class1<dim>
{
   public:
     Class2() : 
       Class1<dim>() {}; 

 };

template <int dim>
class Container
{
  public:
     Container( Class1<dim> & f, int param1) : c1(f), param_(param1) {}

  Class1<dim>  & c1;
      int param_;
 };

 static const int d = 2; 

 int main() 
 {
    int p = 1;
    Class2<d> c2;
    std::vector< Container<d> *> p_list;
    std::vector< Container<d> > list;
    {
      p_list.push_back ( new Container<d> ( c2,p ) ); 
    }
    std::cout<<"from pointers: "<<p_list[0]->param_<<std::endl;

    {
      list.push_back( Container<d> ( c2,p ) );
    }
    std::cout<<"from objects: "<<list[0].param_<<std::endl;
 }


推荐答案

应该标记为虚拟,否则当一个派生类(例如Class2)的实例被销毁时,它的析构函数不会被正确调用。

Firstly, the destructor of Class1 should be marked virtual, otherwise when an instance of a deriving class (Class2 for example) is destroyed, it's destructor wont be called correctly.

对于您的问题,使用对象容器的后果是:

As for your question, the consequences of using a container of objects are:


  • 容器可能需要复制对象,所以您需要确保有一个复制构造函数(您的类在示例中获取由编译器生成的默认值)。复制对象可能会对性能产生影响,您需要正确定义副本的语义(深度或浅度,即是否创建了class1对象的新副本,或者只是复制引用)。

  • 您不能具有任何多态性,因此您不能将Container子类化,然后将基类和子类的实例放在同一个容器中。

  • 根据容器,你的对象将在内存中是连续的(这是一个向量的情况),它可以带来性能优势。

容器的原始指针,那么容器只需要复制指针(更快),你可以添加包含类型的派生实例。缺点是,你必须在使用后手动销毁对象,如前所述,很容易泄漏内存。

If you use a container of raw pointers, then the container only needs to copy pointers (faster) and you can add derived instances of the contained type. The downside is that you'll have to destroy the objects manually after use and as you mentioned, it's easy to leak memory.

shared_ptrs对原始指针有类似的好处/缺点,但是关键的好处是shared_ptr在没有什么东西引用它的时候为你销毁对象,这使得你不太可能引入内存泄漏(但是当涉及异常时这是不可能的)。

shared_ptrs have similar benefits/downsides to raw pointers, but the key benefit is the the shared_ptr destroys the object for you when nothing is referencing it any more, this makes it less likely that you'll introduce memory leaks (but it's still not impossible to do so when exceptions are involved).

鉴于您将这些对象移交进一步处理,我认为基于shared_ptr的方法是一个不错的选择。使用共享ptrs超过原始指针的后果是:

Given that your handing these objects over for further processing, I would say a shared_ptr based approach is a good option. The consequences of using shared ptrs over and above those of raw pointers are:


  • 可能会有性能开销,安全,大多数shared_ptr实现需要检查/设置锁(这可能涉及到对OS的系统调用)。

  • 您可以通过引入对象之间的循环引用来泄漏内存。
  • 你必须使用一个实现C ++ 11或使用外部库的编译器(大多数人使用boost)。

使用shared_ptrs的示例看起来像这样(未测试)。

An example using shared_ptrs would look something like this (not tested).

#include <string>
#include <iostream>
#include <vector>

template<int dim>
class Class1 {
   public:
       Class1() {};
       virtual ~Class1() {}; 

};

template<int dim>
class Class2 : public Class1<dim>
{
    public:
        Class2() : 
        Class1<dim>() {}; 

};

template <int dim>
class Container
{
    public:
       Container( boost::shared_ptr<Class1<dim>> f, int param1) : c1(f), param_(param1) {}

       boost::shared_ptr<Class1<dim>> c1;
       int param_;
};

static const int d = 2;

int main() 
{
    int p = 1;
    boost::shared_ptr<Class1<d>> c2 = boost::make_shared<Class2<d>>();

    std::vector<boost::shared_ptr<Container<d>>> list;
    list.push_back(boost::make_shared<Container<d>>(c2,p));

    std::cout << "from objects: " << list[0]->param_ << std::endl;
}

总之,如果接收容器的代码不存储ref任何地方,你不需要多态性,那么一个容器的对象可能是确定。如果接收容器的代码需要存储在某个地方,和/或您需要多态容器,请使用共享ptrs。

In summary, if the code receiving the containers doesn't store refs to them anywhere, and you don't need polymorphism, then a container of objects is probably ok. If it is necessary for the code receiving the containers to store them somewhere, and/or you want polymorphic containers, use shared ptrs.

这篇关于std :: vector of objects / pointers / smart pointers to pass objects(buss error:10)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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