0

提示コードはstatic変数や関数のコーディングルールを確認してコメントを入力しているものになるのですがタイトル通りですが`常にスタック領域外に置かれることによる利点はなんでしょうか?

Main.cpp
#include <iostream>
#include "Test.hpp"


static int global_Var;
int test_Var = 0;

static Test test;   //static クラスも出来る



void AddFunction();
void AddFunction()
{
    global_Var++;
    static int t;
    t++;
//  staticFunction();
    std::cout << "AddFunction() t: " << t << std::endl;
}

static void staticFunction();
static void staticFunction()
{
    test_Var = 3;

    AddFunction();
    test_Var = 2;
    std::cout << "static Function" << std::endl;
}



int main()
{
    std::cout << staticTestCpp << std::endl;
    sample::Init();
    std::cout << sample::staticSample_Var << std::endl;

    AddFunction();
    AddFunction();
    AddFunction();
    AddFunction();

    staticFunction();

    Test test;

    //std::cout << Test::staticTest_Var << std::endl;   //staticメンバ関数は初期化しないと参照出来ない
    std::cout << Test::staticTest_Var << std::endl;
    std::cout << global_Var << std::endl;


    return 0;
}
Test.cpp
#include "Test.hpp"
#include <iostream>

/* ### Test class ###*/
int Test::staticTest_Var;   //static変数は初期値を入れなくても自動で0が入る。
Test::Test()
{
    std::cout << "test コンストラクタ" << std::endl;
}

void Test::staticTest_Method()
{
    std::cout << "test static メンバ関数" << std::endl;
}

/* ### sample class ###*/
int sample::staticSample_Var = 23;  //static メンバ変数は必ず外で初期化
void sample::Init()
{
    //Method(); //普通の関数は参照出来ない。
    //sample_Var = 2;   //staticメンバ関数はstatic変数しか参照出来ない。
    staticSample_Var = 2;   
    std::cout << "sample Init" << std::endl;
}

void sample::Method()
{
    sample_Var = 2;
    staticSample_Var = 2;   //static変数でも普通の関数では参照できる。
}

sample::sample()
{
    std::cout << "sample コンストラクタ" << std::endl;
}

void sample::staticSample_Method()
{
    std::cout << "sample static メンバ関数" << std::endl;
}


Test.hpp
#ifndef ___TEST_HPP___
#define ___TEST_HPP___

//int testCpp;  //やってはならない

static int staticTestCpp;



/* ### インスタンス生成     可能 ###*/
static class Test
{
public:
    Test();

    static void staticTest_Method();
    const static int staticTest_Var_Const = 0;  //宣言と同時に初期化するにはconstでないとエラーになる。
    static int staticTest_Var;

private:

};

//int Test::staticTest_Var = 0; //ここでは初期化できない。



/* ### インスタンス生成     不可 ###*/
class sample
{
public:
    void Method();

    static void Init();

    static void staticSample_Method();

    static int staticSample_Var;

    int sample_Var;
private:
    sample();

};
#endif

2 件の回答 2

1

基本的に、スタック領域というのはサイズが小さいです(一般的には数Mバイト程度)
ってことで、サイズの大きい変数はスタック領域内には置けません

1

staticを付けるとスタック領域に確保される

staticを付けてもスタック領域には確保されないので質問が成立しません。何かを誤解されているのだとは思いますが、どのような誤解かを推測することはできませんでした。
おおむね次のような関係にあります。

  • staticを付けた場合
    • 常にスタック領域外
  • staticを付けなかった場合
    • 関数内の変数
      • スタック領域
    • 関数外の変数
      • スタック領域外
1
  • 質問文を少し修正しました。常にスタック領域外に置かれることによる利点が知りたいです。
    – user48206
    2022年1月20日 8:02

この質問に回答するには、ログインする必要があります。