D
D
Daniil Demidko2016-02-12 11:11:57
C++ / C#
Daniil Demidko, 2016-02-12 11:11:57

Is it possible in C++ to re-allocate memory on the stack for a variable?

I have a question about the implementation of the stack in C ++ and C # overdue.
C# code example:

// Примитивный тип, очевидно
struct Example{}
// ... 
Example example=new Example(); 
// Для примитивных типов оператор new выделяет память в стеке
// Еще раз выделяем память в стеке
example=new Example();

Now let's move on to C++ and what worries me:
struct Example{};
//...
// Создаем переменную
Example example; // Можно Exemple example=Example(); - то же самое
// А вот и собственно вопрос - что происходит в коде ниже:
exemple=Example();

Is this a re-allocation on the stack for the example variable, or just an assignment in the same memory that was previously allocated?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Adamos, 2016-02-12
@Daniro_San

The = operator for the C++ compiler means "calculate the right side and assign the result of the calculation to the left." What was in the variable before that, which was on the left side, does not play any role at all.

D
Dmitry, 2016-02-12
@EvilsInterrupt

You probably want something like this:

#include <iostream>
using namespace std;

struct Example{
  int a;
};

int main() {
  Example example{5};
  cout << example.a << endl;
  example = Example{101};
  cout << example.a << endl;
  return 0;
}

In other words, every user-defined type has constructors, destructors, and default assignment operators.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question