草庐IT

c++ - 变量 vector 与指针 vector

coder 2024-02-21 原文

我只是好奇使用变量 vector 与使用动态内存指针 vector 的区别,我发现了一些让我困惑的事情。我有一个简单的 main.cpp,看起来像这样,

#include <iostream>
#include <vector>

using namespace std;

class A
{
public:
    A() { x = 2;}
    virtual ~A() { cout << "I'm a dead A\n";}

public:
    int x;
};

class B : public A
{
public:
    B() {x = 4;}
    ~B() { cout << "I'm a dead B\n";}
};

class C : public A
{
public:
    C() { x = 6;}
    ~C() { cout << "I'm a dead C\n";}
};

int main()
{
    cout << "Starting variable list\n";
    std::vector<A> list;

    list.push_back( B() );
    list.push_back( A() );
    list.push_back( B() );
    list.push_back( C() );
    list.push_back( A() );


    for(std::vector<A>::iterator it = list.begin(); it != list.end(); it++)
    {
        cout << it->x << endl;
    }

    cout << "\n\nStarting pointer list\n";

    std::vector<A *> ptrList;

    ptrList.push_back( new B());
    ptrList.push_back( new A());
    ptrList.push_back( new B());
    ptrList.push_back( new C());
    ptrList.push_back( new A());

    for(std::vector<A *>::iterator it = ptrList.begin(); it != ptrList.end(); it++)
    {
        cout << (*it)->x << endl;
    }

    for(std::vector<A *>::iterator it = ptrList.begin(); it != ptrList.end(); it++)
    {
        delete *it;
    }

    system("PAUSE");
    return 0;
}

然后我得到如下所示的打印输出:

Starting variable list
I'm a dead B
I'm a dead A
I'm a dead A
I'm a dead A
I'm a dead A
I'm a dead A
I'm a dead B
I'm a dead A
I'm a dead A
I'm a dead A
I'm a dead A
I'm a dead C
I'm a dead A
I'm a dead A
I'm a dead A
I'm a dead A
I'm a dead A
I'm a dead A
4
2
4
6
2


Starting pointer list
4
2
4
6
2
I'm a dead B
I'm a dead A
I'm a dead A
I'm a dead B
I'm a dead A
I'm a dead C
I'm a dead A
I'm a dead A
Press any key to continue . . .

所有这些破坏发生在普通变量列表中的原因是什么?

最佳答案

在专注于构造/破坏/复制(以及最终优化)的动态之前,有一个您似乎没有意识到的注意事项:值不是多态的

如果B源自 A ,

B b;
A a(b);

不会制作a b 的拷贝.它只会复制 a bA子组件。

与值不同,指针和引用是多态的:

B b;
B* pb = &b;
A* pa = pb;
B* pb2 = const_cast<B*>(pa);

实际上会导致 pa 指向 b 的 A 子组件,但是 pbpb2指向相同的 b .

也就是说,一个 vector<A>包含 values , 因此,

vecotr<A> v;
v.push_back(B());

将导致:

  • 创建一个空的 v ;
  • 创建一个临时的B();
  • 使 v 足够大以包含 A
  • 在 v.end() 处创建一个从临时 B 的 A 子组件复制的 A。
  • 销毁临时B

并且 - 在函数的末尾,

  • 销毁 v(从而销毁其中的 A)

内存现在是干净的。

如果使用指针:

vector<A*> v;
v.push_back(new B());

将导致:

  • 创建一个空的 v
  • 在堆上创建一个B
  • 扩大 v 以包含 A*
  • 将 B 的地址转换为其 A 的子组件地址(对于单继承,它们很可能是相同的)
  • 在 v.end() 处创建一个从 B 的转换地址复制的 A*(请注意,您正在转换指针,而不是对象)。
  • 摧毁v
  • 摧毁其中的A*。
  • 堆上的 B 仍然存在(内存泄漏,因为没有其他方法访问它以删除它)

为避免泄漏,您应该:

  • 在堆栈上创建 B,并获取其地址或...
  • 使用 std::unique_ptr<A>而不是 A*在 vector 中(因此,在 vector 销毁时,unique_ptr 被销毁,其析构函数销毁指向的 A 子对象,具有虚拟析构函数将导致 B 的销毁。

对于上述问题可以通过以下代码给出更有效的演示:

// Compile as g++ -pedantic -Wall -std=c++11

#include <vector>
#include <list>
#include <iostream>

class A
{
public:
    A() { std::cout << "- creating A at " << this << std::endl; }
    A(const A& a) { std::cout << "- creating A at " << this << " from " << &a << std::endl; }
    A& operator=(const A& a) { std::cout << "- assigning A at " << this << " from " << &a << std::endl; return *this; }
    virtual ~A() { std::cout << "- destroying A at " << this << std::endl; }
    virtual void hello() const { std::cout << "- A's hello from " << this << std::endl; }
};

class B: public A
{
public:
    B() { std::cout << "- creating B at " << this << std::endl; }
    B(const B& a) { std::cout << "- creating B at " << this << " from " << &a << std::endl; }
    B& operator=(const B& a) { std::cout << "- assigning B at " << this << " from " << &a << std::endl; return *this; }
    virtual ~B() { std::cout << "- destroying B at " << this << std::endl; }
    virtual void hello() const { std::cout << "- B's hello from " << this << std::endl; }
};

class C: public A
{
public:
    C() { std::cout << "- creating C at " << this << std::endl; }
    C(const C& a) { std::cout << "- creating C at " << this << " from " << &a << std::endl; }
    C& operator=(const C& a) { std::cout << "- assigning C at " << this << " from " << &a << std::endl; return *this; }
    virtual ~C() { std::cout << "- destroying C at " << this << std::endl; }
    virtual void hello() const { std::cout << "- C's hello from " << this << std::endl; }
};

int main()
{
    std::cout << "creating some objects" << std::endl;
    A a1, a2;
    B b1, b2;
    C c1, c2;

    {
        std::cout << "operating with values" << std::endl;
        std::vector<A> valvect;
        valvect.push_back(a1);
        valvect.push_back(a1);
        valvect.push_back(b1);
        valvect.push_back(b1);
        valvect.push_back(c1);
        valvect.push_back(c1);
        valvect.push_back(a2);
        valvect.push_back(a2);
        valvect.push_back(b2);
        valvect.push_back(b2);
        valvect.push_back(c2);
        valvect.push_back(c2);
        for(const auto& x: valvect) x.hello();
        std::cout << "at '}' destroy the value vector" << std::endl;
    }


    {
        std::cout << "operating with pointers" << std::endl;
        std::vector<A*> ptrvect;
        ptrvect.push_back(&a1);
        ptrvect.push_back(&a1);
        ptrvect.push_back(&b1);
        ptrvect.push_back(&b1);
        ptrvect.push_back(&c1);
        ptrvect.push_back(&c1);
        ptrvect.push_back(&a2);
        ptrvect.push_back(&a2);
        ptrvect.push_back(&b2);
        ptrvect.push_back(&b2);
        ptrvect.push_back(&c2);
        ptrvect.push_back(&c2);
        for(const auto& x: ptrvect)
            x->hello();
        std::cout << "at '}' destroy the pointer's vector" << std::endl;
    }

    {
        std::cout << "operating with list of values" << std::endl;
        std::list<A> vallst;
        vallst.push_back(a1);
        vallst.push_back(a1);
        vallst.push_back(b1);
        vallst.push_back(b1);
        vallst.push_back(c1);
        vallst.push_back(c1);
        vallst.push_back(a2);
        vallst.push_back(a2);
        vallst.push_back(b2);
        vallst.push_back(b2);
        vallst.push_back(c2);
        vallst.push_back(c2);
        for(const auto& x: vallst)
            x.hello();
        std::cout << "at '}' destroy the value list" << std::endl;
    }


    {
        std::cout << "operating with list of pointers" << std::endl;
        std::list<A*> ptrlst;
        ptrlst.push_back(&a1);
        ptrlst.push_back(&a1);
        ptrlst.push_back(&b1);
        ptrlst.push_back(&b1);
        ptrlst.push_back(&c1);
        ptrlst.push_back(&c1);
        ptrlst.push_back(&a2);
        ptrlst.push_back(&a2);
        ptrlst.push_back(&b2);
        ptrlst.push_back(&b2);
        ptrlst.push_back(&c2);
        ptrlst.push_back(&c2);
        for(const auto& x: ptrlst)
            x->hello();
        std::cout << "at '}' destroy the pointer's list" << std::endl;
    }



    std::cout << "now finally at '};' destroy the objects created at the beginning" << std::endl;
    return 0;
}

输出结果如下

creating some objects
- creating A at 0x22febc
- creating A at 0x22feb8
- creating A at 0x22feb4
- creating B at 0x22feb4
- creating A at 0x22feb0
- creating B at 0x22feb0
- creating A at 0x22feac
- creating C at 0x22feac
- creating A at 0x22fea8
- creating C at 0x22fea8
operating with values
- creating A at 0x3e3eb8 from 0x22febc
- creating A at 0x3e2434 from 0x22febc
- creating A at 0x3e2430 from 0x3e3eb8
- destroying A at 0x3e3eb8
- creating A at 0x3e2448 from 0x22feb4
- creating A at 0x3e2440 from 0x3e2430
- creating A at 0x3e2444 from 0x3e2434
- destroying A at 0x3e2430
- destroying A at 0x3e2434
- creating A at 0x3e244c from 0x22feb4
- creating A at 0x3e2468 from 0x22feac
- creating A at 0x3e2458 from 0x3e2440
- creating A at 0x3e245c from 0x3e2444
- creating A at 0x3e2460 from 0x3e2448
- creating A at 0x3e2464 from 0x3e244c
- destroying A at 0x3e2440
- destroying A at 0x3e2444
- destroying A at 0x3e2448
- destroying A at 0x3e244c
- creating A at 0x3e246c from 0x22feac
- creating A at 0x3e2470 from 0x22feb8
- creating A at 0x3e2474 from 0x22feb8
- creating A at 0x3e24a0 from 0x22feb0
- creating A at 0x3e2480 from 0x3e2458
- creating A at 0x3e2484 from 0x3e245c
- creating A at 0x3e2488 from 0x3e2460
- creating A at 0x3e248c from 0x3e2464
- creating A at 0x3e2490 from 0x3e2468
- creating A at 0x3e2494 from 0x3e246c
- creating A at 0x3e2498 from 0x3e2470
- creating A at 0x3e249c from 0x3e2474
- destroying A at 0x3e2458
- destroying A at 0x3e245c
- destroying A at 0x3e2460
- destroying A at 0x3e2464
- destroying A at 0x3e2468
- destroying A at 0x3e246c
- destroying A at 0x3e2470
- destroying A at 0x3e2474
- creating A at 0x3e24a4 from 0x22feb0
- creating A at 0x3e24a8 from 0x22fea8
- creating A at 0x3e24ac from 0x22fea8
- A's hello from 0x3e2480
- A's hello from 0x3e2484
- A's hello from 0x3e2488
- A's hello from 0x3e248c
- A's hello from 0x3e2490
- A's hello from 0x3e2494
- A's hello from 0x3e2498
- A's hello from 0x3e249c
- A's hello from 0x3e24a0
- A's hello from 0x3e24a4
- A's hello from 0x3e24a8
- A's hello from 0x3e24ac
at '}' destroy the value vector
- destroying A at 0x3e2480
- destroying A at 0x3e2484
- destroying A at 0x3e2488
- destroying A at 0x3e248c
- destroying A at 0x3e2490
- destroying A at 0x3e2494
- destroying A at 0x3e2498
- destroying A at 0x3e249c
- destroying A at 0x3e24a0
- destroying A at 0x3e24a4
- destroying A at 0x3e24a8
- destroying A at 0x3e24ac
operating with pointers
- A's hello from 0x22febc
- A's hello from 0x22febc
- B's hello from 0x22feb4
- B's hello from 0x22feb4
- C's hello from 0x22feac
- C's hello from 0x22feac
- A's hello from 0x22feb8
- A's hello from 0x22feb8
- B's hello from 0x22feb0
- B's hello from 0x22feb0
- C's hello from 0x22fea8
- C's hello from 0x22fea8
at '}' destroy the pointer's vector
operating with list of values
- creating A at 0x3e2448 from 0x22febc
- creating A at 0x3e24d0 from 0x22febc
- creating A at 0x3e24e8 from 0x22feb4
- creating A at 0x3e2500 from 0x22feb4
- creating A at 0x3e2518 from 0x22feac
- creating A at 0x3e2530 from 0x22feac
- creating A at 0x3e2548 from 0x22feb8
- creating A at 0x3e2560 from 0x22feb8
- creating A at 0x3e2578 from 0x22feb0
- creating A at 0x3e2590 from 0x22feb0
- creating A at 0x3e25a8 from 0x22fea8
- creating A at 0x3e25c0 from 0x22fea8
- A's hello from 0x3e2448
- A's hello from 0x3e24d0
- A's hello from 0x3e24e8
- A's hello from 0x3e2500
- A's hello from 0x3e2518
- A's hello from 0x3e2530
- A's hello from 0x3e2548
- A's hello from 0x3e2560
- A's hello from 0x3e2578
- A's hello from 0x3e2590
- A's hello from 0x3e25a8
- A's hello from 0x3e25c0
at '}' destroy the value list
- destroying A at 0x3e2448
- destroying A at 0x3e24d0
- destroying A at 0x3e24e8
- destroying A at 0x3e2500
- destroying A at 0x3e2518
- destroying A at 0x3e2530
- destroying A at 0x3e2548
- destroying A at 0x3e2560
- destroying A at 0x3e2578
- destroying A at 0x3e2590
- destroying A at 0x3e25a8
- destroying A at 0x3e25c0
operating with list of pointers
- A's hello from 0x22febc
- A's hello from 0x22febc
- B's hello from 0x22feb4
- B's hello from 0x22feb4
- C's hello from 0x22feac
- C's hello from 0x22feac
- A's hello from 0x22feb8
- A's hello from 0x22feb8
- B's hello from 0x22feb0
- B's hello from 0x22feb0
- C's hello from 0x22fea8
- C's hello from 0x22fea8
at '}' destroy the pointer's list
now finally at '};' destroy the objects created at the beginning
- destroying C at 0x22fea8
- destroying A at 0x22fea8
- destroying C at 0x22feac
- destroying A at 0x22feac
- destroying B at 0x22feb0
- destroying A at 0x22feb0
- destroying B at 0x22feb4
- destroying A at 0x22feb4
- destroying A at 0x22feb8
- destroying A at 0x22febc

关于c++ - 变量 vector 与指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13154057/

有关c++ - 变量 vector 与指针 vector的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  3. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  4. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  5. ruby-on-rails - 使用 ruby​​ 将多个实例变量转换为散列的更好方法? - 2

    我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。

  6. ruby - Rack:如何将 URL 存储为变量? - 2

    我正在编写一个简单的静态Rack应用程序。查看下面的config.ru代码:useRack::Static,:urls=>["/elements","/img","/pages","/users","/css","/js"],:root=>"archive"map'/'dorunProc.new{|env|[200,{'Content-Type'=>'text/html','Cache-Control'=>'public,max-age=6400'},File.open('archive/splash.html',File::RDONLY)]}endmap'/pages/search.

  7. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  8. ruby-on-rails - 应用程序的名称是否可以作为变量使用? - 2

    当我创建一个Rails应用程序时,控制台:railsnewfoo我的代码可以使用字符串“foo”吗?puts"Yourapp'snameis"+app_name_bar 最佳答案 Rails.application.class将为您提供应用程序的全名(例如YourAppName::Application)。从那里您可以使用Rails.application.class.parent获取模块名称。 关于ruby-on-rails-应用程序的名称是否可以作为变量使用?,我们在StackOve

  9. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  10. ruby - 在 Ruby 中,在类方法的上下文中,什么是实例变量和类变量? - 2

    如果我有以下一段Ruby代码:classBlahdefself.bleh@blih="Hello"@@bloh="World"endend@blih和@@bloh到底是什么?@blih是Blah类中的一个实例变量,@@bloh是Blah类中的一个类变量,对吗?这是否意味着@@bloh是Blah的类Class中的一个变量? 最佳答案 人们似乎忽略了该方法是类方法。@blih将是常量Bleh的类Class实例的实例变量。因此:irb(main):001:0>classBlehirb(main):002:1>defself.blehirb

随机推荐