警告:临时地址-C

warning: taking address of temporary - C++

本文关键字:地址 警告      更新时间:2023-10-16

以下代码是"简单说明的设计模式"中的一个示例。我尝试使用建议的其他问题的建议,但结果不好。我该如何找出这个问题:

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;

请注意,如果simple不再存在后使用command[0],这将遇到相同的问题。更现实的代码(例如,"玩具 main()中的所有内容",如"评论中的无用)可以很容易地存在commands[0]的问题,并且在对象指出的对象指向停止之后,它也会导致不确定的行为。 - 但是编译器能够认识到并发出警告的可能性较小。

SimpleCommand(&object, &Number::dubble)

创建一种叫做 rvalue 的东西。这是一个临时值,将在声明结束时被销毁,因此您不应参考它。