【问题标题】:Taking address of temporary [-fpermissive]获取临时地址 [-fpermissive]
【发布时间】:2016-12-23 09:13:11
【问题描述】:

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

这是我的 sn-p 代码。来自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()

所以,我尝试在互联网上查找。正如他们所说:

&A() 正在创建一个临时对象,该对象在退出完整表达式时自动销毁...

当我换了error line

&One(), &Two()

new One(), new Two()

然后,它起作用了。

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

delete array[i];

【问题讨论】:

  • 你必须弄清楚你想在这里问哪个问题。您目前正在询问两个不相关的问题。

标签: c++


【解决方案1】:

借助现代 C++ 功能(11 及更高版本),您可以使用 std::vector&lt;std::unique_ptr&lt;Base&gt;&gt; 处理此类多态数组。 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 原语 这么低级的动作。

【讨论】:

    猜你喜欢
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2011-03-21
    • 1970-01-01
    相关资源
    最近更新 更多