C++ completely erase (or reset) all values of a struct?
So, I was just wondering how could we completely erase or reset a structure so it could be reused?
I just typed this up, here you go:
3 Answers 3
You can just assign a constructed temporary to it:
If for some reason I was hell-bent on keeping the same object constantly, I would just write a reset method that would reset all the values back to what they were.
Something similar to this:
Good practice is to avoid that type of construct (using the same variable for two different semantics meanings, having reset it in the meantime). It will inevitably create a weird bug later on when you (or somebody else) modify your code and forgets you shared a variable for two different uses.
The only justification would be to spare some memory space but:
- It is very unlikely that you actually need such an optimisation.
- Even if you do, the compiler will usually figure out a variable on the stack is no longer use and can be discarded, the new variable you would create will thus effectively replace the first one. You do not need to care about sparing the memory yourself.
- If your variables are on the heap, you are better off just using two different pointers.
But if you really want to do this reset, you must write a method to do it. There is not built-in way in C++, because it would actually require calling the destructor and then the constructor again.
The solution my_struct = Part() works only if your destructor is trivial. Let’s say you have allocated pointer in your std::vector , you would have to properly delete every pointer before emptying the vector . That’s why it cannot be done automatically: the cleanup of the structure may require special treatment rather than plain forgetting.
C ++ полностью стереть (или сбросить) все значения структуры?
Итак, мне просто интересно, как мы можем полностью стереть или сбросить структуру, чтобы ее можно было использовать повторно?
Я только что напечатал это, вот и вы:
Решение
Вы можете просто назначить ему созданный временный объект:
Другие решения
Если бы по какой-то причине я был одержим постоянным сохранением одного и того же объекта, я бы просто написал reset метод, который будет сбрасывать все значения обратно к тому, что они были.
Что-то похожее на это:
Хорошей практикой является избегать такого типа конструкции (используя одну и ту же переменную для двух разных значений семантики, сбросив ее за это время). Это неизбежно создаст странную ошибку позже, когда вы (или кто-то еще) измените свой код и забудете, что вы использовали переменную для двух разных целей.
Единственным оправданием было бы сэкономить место в памяти, но:
- Маловероятно, что вам действительно нужна такая оптимизация.
- Даже если вы это сделаете, компилятор обычно обнаружит, что переменная в стеке больше не используется и может быть отброшена, поэтому новая переменная, которую вы создадите, эффективно заменит первую. Вам не нужно заботиться о сохранении памяти самостоятельно.
- Если ваши переменные находятся в куче, вам лучше использовать два разных указателя.
Но если вы действительно хотите сделать этот сброс, вы должны написать метод, чтобы сделать это. В C ++ нет встроенного способа, потому что для этого потребуется вызов destructor а затем constructor снова.
Решение my_struct = Part() работает только если ваш destructor тривиально. Допустим, вы выделили указатель на ваш std::vector вам бы пришлось правильно delete каждый указатель перед очисткой vector , Вот почему это не может быть сделано автоматически: очистка конструкции может потребовать специальной обработки, а не простого забывания.
Как очистить структуру c
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
- ProfileText
- Sign in
Answered by:
Question
I was wondering if there is a good way in C# 2.0 to clear/empty these structs ?
Thanks for any help.
First struct:
public struct ClientLogin
<
public int Install_cod;
public string UserID;
>
Second struct:
public struct ClientSettings
<
public string UploadTime;
public int IntervalInHours;
public List < TFileFilter > FileFilter;
>
public class TFileFilter
<
private int fileType_cod;
private bool includeSubDir;
private string fileFilter;
Answers
Simply assign default(ClientLogin) or default(ClientLogin) to a variable. For example:
| ClientLogin clientLogin; |
| //. |
| clientLogin = default (ClientLogin); |
- Marked as answer by d_vm23 Wednesday, August 20, 2008 12:23 PM
- Unmarked as answer by d_vm23 Wednesday, August 20, 2008 1:17 PM
- Marked as answer by d_vm23 Wednesday, August 20, 2008 2:28 PM
Is there any CLR difference when performing default versus performing a new instantiation and assigning it to the variable? David Morton — http://blog.davemorton.net/
No difference. It’s just more clear what you’re doing when you write "default(MyStruct)" instead of "new MyStruct()". http://www.peterRitchie.com/blog
- Marked as answer by d_vm23 Wednesday, August 20, 2008 2:28 PM
All replies
Just set the variables that represent these structs to new structs.
David Morton — http://blog.davemorton.net/
I was hoping there was a method I could send the struct to like in Delphi like:
ClearRecord( MyStruct, SizeOf( MyStruct) );
< ClearRecord:
Sets the bytes of record R to 0.
Zero NBytes of structure R. Note SizeOf(R) = 0.
>
procedure ClearRecord(var R; NBytes: Integer);
begin
assert( NBytes > 0 );
FillChar( R, NBytes, 0 );
end; // procedure ClearRecord(var R; NBytes: Integer);
There isn’t a built in method that does that.
The reason I suggested simply setting the instances to new instances, is because that is essentially the same thing. The values of a struct are created having the default values (null for reference types, and 0/false for numeric/boolean types).
Because structs are value types and not reference types, setting them to new instances will merely remove the old object from the stack, and replace it with the newly instantiated struct.
But to answer your question, there is no pre-created method that does this for structs. This is already done in the default constructor for a struct.
Как удалить запись из структуры?
Не могу сделать удаление книги, нужно вводить название с клавиатуры, и еще прошу помочь с заданием: по запросу выводится информация о книгах, изданных после года, введенного с клавиатуры. Буду благодарен помощи, никак не могу решить
- Вопрос задан более двух лет назад
- 536 просмотров
- Вконтакте
В чем проблема? Не можете сделать ввод названия с клавиатуры? Скопируйте код с готовой функции make().
Для удаления надо пройтись по всему списку — это уже делается в функции main при выводе библиотеки (кстати, там не нужен pLibrary. Можно совместить цикл while и цикл for после него. Вы проходитесь циклом по элементам списка, кладете их в массив и потом проходитесь по массиву. Достаточно просто делать с ними, что вам надо прямо в первом цикле).
Потом, вместо вывода сравнивайте название текущей книги с введенным с клавиатуры (функция strcmp). Если совпало, то надо предыдущему элементу в next присвоить next текущей записи и потом вызвать free() от текущей записи и вывалиться из цикла через break.
Да, единственная сложность — надо поддерживать указатель на предыдущую запись, а лучше даже на next у предыдущей записи (это будет LIBRARY**). Тогда для удаления надо просто head->next записать туда и текущий элемент выпадет из списка. Перед переходом к следующему элементу в цикле while просто перезапишите этот указатель на &head->next. Изначально он должен быть &head. Таким образом можно удалить даже первый элемент списка без разбора случаев.