gpt4 book ai didi

c++ - 获取临时地址 [-fpermissive]

转载 作者:行者123 更新时间:2023-11-28 01:55:42 25 4
gpt4 key购买 nike

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

这是我的代码片段。来自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() is creating a temporary object which gets destructed on exit of the full expression automagically...

当我更改错误行

&One(), &Two()

new One(), new Two()

然后,它起作用了。

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

delete array[i];

最佳答案

借助现代 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

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

Try not to handle memory management manually, use STL primitives for such low-level actions.

关于c++ - 获取临时地址 [-fpermissive],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com