c++ - 警告 : taking address of temporary - C++

标签 c++

<分区>

以下代码是《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;

请注意,如果在 simple 不复存在后使用 command[0] 也会遇到同样的问题。更现实的代码(例如,并非玩具 main() 中的所有内容,如“评论中无用”所指出的)很容易导致 commands[0] 继续存在的问题 -并被使用 - 在它指向的对象不复存在之后。这也会导致未定义的行为 - 但编译器不太可能识别并发出警告。

关于c++ - 警告 : taking address of temporary - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42398340/

相关文章:

c++ - (MATLAB/C++) 是否可以将函数作为参数传递给 C++ MEX 函数?

c++ - 我如何访问静态类成员?

c++ - 在 C++ 中避免类定义中的循环依赖

c++ - 'delete' 函数之前的预期 Unqualified-Id

c++ - 用 Poco :Condition 唤醒两个线程

c++ - 文件处理在 while 循环中不起作用

c++ - 将矩阵写入文件

android ndk 通信不同的 c++ 项目

c++ - 在优胜美地编译caffe

C++ 父类(super class)数组还访问子类方法?