相关疑难解决方法(0)

什么是int&mean

一个C++问题,

我知道

int* foo(void)
Run Code Online (Sandbox Code Playgroud)

foo将返回一个指向int类型的指针

怎么样

int &foo(void)
Run Code Online (Sandbox Code Playgroud)

什么回来了?

非常感谢!

c++ types pointers

18
推荐指数
3
解决办法
5万
查看次数

返回静态局部变量作为引用

当作为引用返回并作为指针直接传递给另一个函数时,静态变量会发生什么?显然,变量在函数返回后仍然存在,但关于这整个概念的一些事情让我感到烦恼.此时是数据后续的内存,被静态变量占用,被释放了吗?当我不再需要它时,运行时会神奇地注意到它,比如某种垃圾收集吗?

举个例子:

SDL_Rect* XSDL_RectConstr(int x, int y, int w, int h)
{
    static SDL_Rect rect;
    rect.x = x;
    rect.y = y;
    rect.w = w;
    rect.h = h;

    return ▭
}

void mainLoop()
{
    while(isRunning)
    {
        pollEvents();
        SDL_BlitSurface(someSurface, XSDL_RectConstr(0, 0, 100, 100), screen, NULL);
        SDL_Flip(screen);
    }
}
Run Code Online (Sandbox Code Playgroud)

rectSDL_BlitSurface()返回后会发生什么?我看不出它什么时候会被释放.这不是某种内存泄漏吗?

c++ static memory-management local

13
推荐指数
3
解决办法
6117
查看次数

在C++中返回对静态局部变量的引用

这个问题只是为了让我更好地理解C++中的静态变量.

我认为如果它被声明为静态,我可以在C++中返回对局部变量的引用,因为变量应该在函数返回后生效.为什么这不起作用?

#include <stdio.h>
char* illegal()
{
  char * word = "hello" ;
  return word ;
}

char* alsoNotLegal()
{
  static char * word = "why am I not legal?" ;
  return word ;
}


int main()
{
  // I know this is illegal
  //char * ill = illegal();
  //ill[ 0 ] = '5' ;
  //puts( ill ) ;

  // but why is this? I thought the static variable should "live on" forever -
  char * leg = alsoNotLegal() ; …
Run Code Online (Sandbox Code Playgroud)

c++

10
推荐指数
1
解决办法
7092
查看次数

为什么可以从外部通过指针或引用访问静态本地对象?

如您所知,局部静态变量不能在函数外部通过名称访问,而是可以通过指针或对其的引用来访问。因此,以下代码格式正确。

但为什么?我知道这个事实是事实,但没有根据。实际上我想要的是C ++标准的相关摘录。我正在阅读,但最终没有找到证据。有人可以给我摘录或提示找我吗(因为仅在文档中搜索“ static”会导致一百多个匹配)?

#include <iostream>
using namespace std;

class Test {

    public:

        int * f(int i) const {
            static int j;
            j += i;
            cout << "now j = " << j << "\n";
            return &j;
        }

        int & g(int i) const { //same as above but handle reference
            static int k;
            k += i;
            cout << "now k = " << k << "\n";
            return k;
        }

};

int main() {

    Test t;

    int *p = …
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer

8
推荐指数
1
解决办法
164
查看次数