取临时[-fpermissive]的地址

时间:2016-12-22 07:59:26

标签: c++

我知道这个问题已经回答了。但我只想确认一下我的理解。

这是我的代码段。它来自this

#include <iostream>
using namespace std;

class Base
{
    void a() { cout << "a  "; }
    void c() { cout << "c  "; }
    void e() { cout << "e  "; }

    // 2. Steps requiring peculiar implementations are "placeholders" in base class
    virtual void ph1() = 0;
    virtual void ph2() = 0;

  public:

    // 1. Standardize the skeleton of an algorithm in a base class "template method"
    virtual ~Base() = default;
    void execute()
    {
        a();
        ph1();
        c();
        ph2();
        e();
    }
};

class One: public Base
{
    // 3. Derived classes implement placeholder methods
    /*virtual*/ void ph1() { cout << "b  "; }
    /*virtual*/ void ph2() { cout << "d  "; }
};

class Two: public Base
{
    /*virtual*/ void ph1() { cout << "2  "; }
    /*virtual*/ void ph2() { cout << "4  "; }
};

int main()
{
  Base *array[] =
  {
      &One(), &Two()
  };
  for (int i = 0; i < 2; i++)
  {
      array[i]->execute();
      cout << '\n';
  }
}

编译时,它会将错误标记为:

error: taking address of temporary [-fpermissive]
&One(), &Two()
error: taking address of temporary [-fpermissive]
&One(), &Two()

所以,我试着在网上找到。正如他们所说:

  

&amp; A()正在创建一个临时对象,在自动退出完整表达式时会被破坏......

当我更改error line

&One(), &Two()

new One(), new Two()

然后,它有效。

但是,我如何使原始代码像作者写的那样起作用?我应该使用delete之类的

吗?
delete array[i];

1 个答案:

答案 0 :(得分:2)

使用现代C ++功能(11及以上版本),您可以使用std::vector<std::unique_ptr<Base>>处理此类多态数组。 vector允许自动销毁和扩展,unique_ptr会自行销毁对象:

std::vector<std::unique_ptr<Base>> array;
array.emplace_back(new One());
array.emplace_back(new Two());
for(auto &p : array)
    p->execute();
// no explicit cleanup is required here

您可以选择其他智能指针类作为矢量元素,甚至可以使用std::array作为固定大小的容器,但所有方法的总体思路都是相同的:

  

尽量不要手动处理内存管理,使用STL原语   这种低级别的行动。