Skip to content

Instantly share code, notes, and snippets.

@Zulan
Last active November 1, 2015 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zulan/1d80b795afb357e94b73 to your computer and use it in GitHub Desktop.
Save Zulan/1d80b795afb357e94b73 to your computer and use it in GitHub Desktop.
#include <memory>
struct node
{
int value;
node* next;
};
struct smart_node
{
int value;
std::unique_ptr<smart_node> next;
};
void clear(node& root)
{
node* current = root.next;
root.next = nullptr;
while (current != nullptr) {
node* next = current->next;
delete current;
current = next;
}
}
void clear(smart_node& root)
{
std::unique_ptr<smart_node> current = std::move(root.next);
while (current) {
std::unique_ptr<smart_node> next = std::move(current->next);
current = std::move(next);
}
}
// NOTE: I am not 100% sure if the following would be generically correct in case of non-standard delters
// current = std::move(current->next);
// The briefest alternative would be
// current.reset(current->next.release());
// With the default deleter all three options should produce the same assembler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment