Closed. This question is off-topic。它当前不接受答案。
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
2年前关闭。
以下代码是一本书“ Design Patterns Explained Simply”中的示例。我尝试使用其他问题的建议方法,但结果不佳。我该如何解决这个问题:
“警告:以临时地址为准”?
在这种情况下,
只需像处理其他对象一样进行操作:构造对象,然后存储其地址。
请注意,如果在
想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
2年前关闭。
以下代码是一本书“ Design Patterns Explained Simply”中的示例。我尝试使用其他问题的建议方法,但结果不佳。我该如何解决这个问题:
commands[0] = &SimpleCommand(&object, &Number::dubble);
“警告:以临时地址为准”?
#include <iostream>
#include <vector>
using namespace std;
class Number
{
public:
void dubble(int &value)
{
value *= 2;
}
};
class Command
{
public:
virtual void execute(int &) = 0;
};
class SimpleCommand: public Command
{
typedef void(Number:: *Action)(int &);
Number *receiver;
Action action;
public:
SimpleCommand(Number *rec, Action act)
{
receiver = rec;
action = act;
}
/*virtual*/void execute(int &num)
{
(receiver->*action)(num);
}
};
class MacroCommand: public Command
{
vector < Command * > list;
public:
void add(Command *cmd)
{
list.push_back(cmd);
}
/*virtual*/void execute(int &num)
{
for (unsigned int i = 0; i < list.size(); i++)
list[i]->execute(num);
}
};
int main()
{
Number object;
Command *commands[3];
commands[0] = &SimpleCommand(&object, &Number::dubble); // "warning: taking address of temporary"
MacroCommand two;
two.add(commands[0]);
two.add(commands[0]);
commands[1] = &two;
MacroCommand four;
four.add(&two);
four.add(&two);
commands[2] = &four;
int num, index;
while (true)
{
cout << "Enter number selection (0=2x 1=4x 2=16x): ";
cin >> num >> index;
commands[index]->execute(num);
cout << " " << num << '\n';
}
}
最佳答案
令人讨厌的行是第三行。
Number object;
Command *commands[3];
commands[0] = &SimpleCommand(&object, &Number::dubble); // "warning: taking address of temporary"
在这种情况下,
SimpleCommand(&object, &Number::dubble)
构造一个临时语句,该临时语句在语句末尾将不复存在,并且&
接受其地址。因此,警告-指针将悬空(指向不再存在的对象)。对该指针的任何取消引用都将导致未定义的行为。不需要编译器来诊断此问题,但是您的帮助正在使您受益。只需像处理其他对象一样进行操作:构造对象,然后存储其地址。
SimpleCommand simple(&object, &Number::dubble);
commands[0] = &simple;
请注意,如果在
command[0]
不再存在后使用simple
,也会遇到相同的问题。更现实的代码(例如,并非玩具main()
中的所有内容,如“在注释中无用”所指出的那样)很容易会在对象指向的对象不再存在后,继续存在commands[0]
并被使用的问题。还会导致未定义的行为-但编译器不太可能识别出该行为并发出警告。关于c++ - 警告:接收临时地址-C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42398340/