警告:临时地址-C
warning: taking address of temporary - C++
以下代码是"简单说明的设计模式"中的一个示例。我尝试使用建议的其他问题的建议,但结果不好。我该如何找出这个问题:
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 的东西。这是一个临时值,将在声明结束时被销毁,因此您不应参考它。
相关文章:
- 警告处理为错误这里有什么问题
- 将数组的地址分配给变量并删除
- 空基优化子对象的地址
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在C++中打印指向不同基元数据类型的指针的内存地址
- cppcheck在const std::string[]上引发警告
- 如何在c++程序中找到函数的地址
- GCC对可能有效的代码抛出init list生存期警告
- 如何在BST的这个简单递归实现中消除警告
- libmysql:警告:返回局部变量"行"的地址(C++/C)
- 获取“将返回值分配给新变量”的警告和输出是内存地址
- 警告:临时地址-C
- 警告:返回局部变量'buffer'地址
- 警告:返回局部变量"角度"的地址 [-Wreturn-local-addr]
- 警告:取临时地址
- C/C++警告:具有BDADDR_ANY蓝牙库的临时地址
- 警告:获取标签的地址是不标准的
- 如果我们在c++中使用static关键字删除[-Wreturn local-addr](警告:返回本地变量的地址),可以
- 为什么返回局部变量或临时变量的地址只是警告而不是错误?