本文介绍了错误:取临时地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经问了很多,但是没有答案可以帮助我解决我的特定问题.

I know that this question was already asked a lot but non of the answers could help me with my specific problem.

我遇到了著名的临时地址"错误.据我了解,这是因为我正在尝试将临时对象转换为指针.

I get the famous "taking adress of temporary" error. And as far as I understood that's because I am trying to convert a temporary object to a pointer.

但是这里有人可以解决这个问题吗?

But does anyone here has a solution to how I can fix this here?

发生错误的代码如下:

newGame = &MenuOption(optionNewGame, text_new_game.width, 2, 0);

newGame的声明如下:

The declaration of newGame looks like this:

MenuOption *newGame;

一个错误看起来像这样:

An the error looks like this:

1>  c:/path/to/project/MainMenu.h:27:65: error: taking address of temporary [-fpermissive]
1>     newGame = &MenuOption(optionNewGame, text_new_game.width, 2, 0);
1>                                                                   ^

推荐答案

您正在创建MenuOption类的临时对象.然后,将该临时对象的地址存储在newGame中.离开控制块后,临时对象将被删除,您的指针将变为悬空指针".

You are creating a temporary object of your MenuOption class. Then you store the address of this temporary object in newGame. Once the control block is left, the temporary object will be deleted and your pointer becomes a 'dangling pointer'.

解决方案:

  • MenuOption newGame(optionNewGame, text_new_game.width, 2, 0);
  • newGame = new MenuOption(optionNewGame, text_new_game.width, 2, 0);
  • 使用unique_ptr:
    std::unique_ptr< MenuOption> newGame;
    newGame.reset( new MenuOption(optionNewGame, text_new_game.width, 2, 0));
  • MenuOption newGame(optionNewGame, text_new_game.width, 2, 0);
  • newGame = new MenuOption(optionNewGame, text_new_game.width, 2, 0);
  • use unique_ptr:
    std::unique_ptr< MenuOption> newGame;
    newGame.reset( new MenuOption(optionNewGame, text_new_game.width, 2, 0));

这篇关于错误:取临时地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 15:07