在运行时赋值后只读的变量?

发布于 2024-12-11 12:48:41 字数 346 浏览 0 评论 0原文

这里是相当新的程序员,并对愚蠢的问题提前致歉。

我在程序中有一个 int 变量,用于确定某些结构中数组的长度。我曾经将它作为 const int 放在我的标头中。现在,我想分叉我的程序,根据给出的参数为变量赋予不同的值,但在运行时分配它后将其保持为只读。

我必须这样做的一些想法。有优选的方式吗?

  1. 在我的标头中声明一个 const int * 并将其分配给我的主函数中的 const int ,但这看起来很笨拙。
  2. 在我的 main 函数中将其设为普通的 int
  3. 调用函数时将变量作为参数传递。
  4. 还有一些我还没想到的事情。

Fairly new programmer here, and an advance apology for silly questions.

I have an int variable in a program that I use to determine what the lengths of my arrays should be in some of my structures. I used to put it in my header as a const int. Now, I want to fork my program to give the variable different values depending on the arguments given in, but keep it read-only after I assign it at run-time.

A few ideas I've had to do this. Is there a preferred way?

  1. Declare a const int * in my header and assigning it to a const int in my main function, but that seems clunky.
  2. Make it a plain int in my main function.
  3. Pass the variable as an argument when the function is called.
  4. Something else I haven't thought of yet.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

妳是的陽光 2024-12-18 12:48:41

我会使用函数静态变量和简单函数。观察:

int GetConstValue(int initialValue = 0)
{
  static int theValue = initialValue;
  return theValue;
}

由于这是一个函数级静态变量,因此它仅在第一次初始化。因此,initialValue 参数在函数第一次运行后就没用了。因此,您需要做的就是确保该函数的第一次调用是对其进行初始化的调用。

I'd use a function-static variable and a simple function. Observe:

int GetConstValue(int initialValue = 0)
{
  static int theValue = initialValue;
  return theValue;
}

Since this is a function-level static variable, it is initialized only the first time through. So the initialValue parameter is useless after the first run of the function. Therefore, all you need to do is ensure that the first call of the function is the one that initializes it.

清浅ˋ旧时光 2024-12-18 12:48:41

C++ 没有为此提供内置解决方案,但如果您确实想确保 int 只分配一次,您可以构建自己的特殊 int 类:

class MyConstInt
{
public: 
    MyConstInt(): assigned(false) {}
    MyConstInt& operator=(int v)
    {
        assert(!assigned); 
        value = v; 
        assigned = true; 
        return *this; 
    }   
    operator int() const 
    { 
        assert(assigned); 
        return value; 
    }
private: 
    int value; 
    bool assigned; 
}; 


MyConstInt mi; 
//  int i = mi;         //  assertion failure; mi has no value yet
mi = 42; 
//  mi = 43;        //  assertion failure; mi already has a value
int* array = new int[mi]; 

C++ doesn't have a built-in solution for this, but if you really want to make sure that your int is only assigned once, you can build your own special int class:

class MyConstInt
{
public: 
    MyConstInt(): assigned(false) {}
    MyConstInt& operator=(int v)
    {
        assert(!assigned); 
        value = v; 
        assigned = true; 
        return *this; 
    }   
    operator int() const 
    { 
        assert(assigned); 
        return value; 
    }
private: 
    int value; 
    bool assigned; 
}; 


MyConstInt mi; 
//  int i = mi;         //  assertion failure; mi has no value yet
mi = 42; 
//  mi = 43;        //  assertion failure; mi already has a value
int* array = new int[mi]; 
未蓝澄海的烟 2024-12-18 12:48:41

您到底什么时候知道正确的值?如果您从文件或其他内容中读取它,您可以直接说:

const int n = determine_correct_value();

When exactly do you know the correct value? If you read it from a file or whatever, you can just say:

const int n = determine_correct_value();
束缚m 2024-12-18 12:48:41

我很想说你想要的没有意义。常量是指不会改变其值的东西,而不是可能改变其值一次或两次的东西。如果你想要一个全局变量,只需将其设为非常量即可。

另一方面,如果您有作用域常量值,则只需同时声明和初始化它们,遵循一般 C++ 准则来声明尽可能接近使用站点。例如,在以下局部范围中标记常量的使用:

for (auto it = v.begin(), end = v.end(); it != end; ++it)
{
  const Foo & x = *it;
  const std::size_t n = x.get_number_of_bars();

  // use x and n ...

  const bool res = gobble(x, zip(n));
  if (res && shmargle(x)) { return 8; }
}

如果变量的值已通过其他方式已知,则编译器甚至可能选择根本不为变量生成任何特殊代码。

I'm tempted to say that what you want doesn't make sense. A constant is something that doesn't change its value, not something that maybe changes its value once or twice. If you want a global variable, just make it non-constant.

On the other hand, if you have scope-constant values, you would just declare and initialize them at the same time, following the general C++ guideline to declare as close to the usage site as possible. For example, mark the use of constants in the following local scope:

for (auto it = v.begin(), end = v.end(); it != end; ++it)
{
  const Foo & x = *it;
  const std::size_t n = x.get_number_of_bars();

  // use x and n ...

  const bool res = gobble(x, zip(n));
  if (res && shmargle(x)) { return 8; }
}

Here the compiler may even choose not to generate any special code for the variables at all if their value is already known through other means.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文