Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a template class Array that has a buffer type vector.
template <typename T>
class Array
{
protected:
std::vector<T> buffer;
......
}
I want to implement the destructor ~Array(); for this buffer. Any ideas on how to do it?
The default destructor is already releasing the memory of vector, you don't need to define one here.
If you want to free memory of the vector explicitly, then try swap technique whenever you want:
std::vector<T>().swap(buffer);
Any ideas on how to do it?
It depends completely on what you've designed the class and its destructor to do.
The best option, when ever it does what is needed, is to not have a user declared destructor at all, but the implicitly generated one instead. In other words, follow the rule of 0 when possible.
I want to delete the allocated memory of the buffer
All member variables are destroyed automatically. The destructor of the vector deallocates its internal buffer. There is no need for a custom destructor here.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
After calling and using the function, I can access the parameters through the pointer. And I think the parameters are kept in memory. I'm trying to delete the parameters after using the code below.
int MyFunction(int p1,int p2)
{
int total = p1 + p2;
delete& p1;
delete& p2;
return total;
}
and using this
int a = MyFunction(15, 30);
(my project name) initiated a breakpoint.I get an error. How do I delete parameters ?
Your function parameters are passed by value, so they are allocated automatically, not dynamically. You cannot delete them. Being automatically allocated, they will also be automatically deallocated when the function returns, so just skip trying to delete them and go straight to returning.
You can only delete objects allocated on heap (via new).
The parameters to the function are allocated on stack before function call and the runtime "removes" them once the function exits.
(The removal just means that the stack pointer is moved to look as if the parameters no longer exist)
How to delete function parameter?
In general, you shouldn't delete arbitrary variables. You should only delete pointers that you explicitly allocated with new somewhere else in your code.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
If I make a vector of pointers of type of some defined class and put a pointer to an object of type of an inherited one of the first one in it, wont the pointer pointing to next address be changed to point to shifted address because of existence of new data members in the inherited class pointed by the previous one.
so If I defined an array with new of type of the base class and then put an object of type of the driven class, how would compiler deal with the modification of the start of the address of the next pointer. shouldn't it be shifted or something like that to make some bytes available for the previous one.
If you define a std::vector<BaseClass> where BaseClass is your base class and then put a DerivedClass type into that vector where DerivedClass is your derived class, you will get slicing. Meaning any extra data members in the derived class are lost.
Because of that, what you would normally do is define a std::vector<BaseClass *> which is a vector of base class pointers. Now you can put base class pointers and derived class pointers in your vector and there is no slicing.
You are storing pointers in the vector. All pointers are the same size.
Note, in the real world you would probably not user raw pointers but some version of a smart pointer to reduce the chance of memory leaks (i.e. forgetting to free a pointer).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am looking for a more in detail answer, rather than UB is UB.
I have a piece of legacy code that I know is the culprit of an exception. We previously memset a vector, and once it was changed to an unordered_map it threw an exception on destruction. What in the source code makes memsetting a vector differ from an unordered_map? They both interact with contiguous memory...
In our code we have this. (I apologize for pseudo code, but the point should still be understandable...)
class B
{
std::vector<CustomObject> vect;
};
struct STRUCT_A
{
B b;
};
Later on we do this...
STRUCT_A m_struct_a;
memset(&m_struct_a, 0, sizeof(STRUCT_A));
This works perfectly fine even if we memset an stl::container! However, if we change class B to have a map then an exception occurs on the destructor.
class B
{
std::map<CustomObject> vect;
};
So I thought it had to do with the vector being contiguous, so I changed it to an unordered_map
class B
{
std::unordered_map<CustomObject> vect;
};
An exception is still thrown on the destructor. I thought it was pretty interesting, and thought it was a good question to ask...
Yes it is indeed an act of absolute insanity to ::memset an instance of a class that contains an STL container.
Thinking more generally, you can only call memset on an object that is trivially copyable. Otherwise the behaviour of your program is undefined.
For more details on that, see http://en.cppreference.com/w/cpp/string/byte/memset and http://en.cppreference.com/w/cpp/types/is_trivially_copyable
Take a look at the source for your implementation's containers.
In libstdc++, the destructor for std::vector calls CustomObject::~CustomObject() for each element in the range [begin(), end()) and then deallocates the memory. Since you memset the vector to 0, begin() == end() == 0, the range is empty and the member's destructor is never called. Similarly, the deallocation is fine since it checks that the storage is non-null before deallocating.
In std::map, the destructor tries to walk the nodes of the _Rb_tree, which fails because the root node has null pointers. In std::unordered_map, the destructor calls __builtin_memset on the bucket array, which fails because the pointer to the array has been cleared.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Lets assume I have the following class:
class A
{
public:
A() {}
};
I need to declare a global instance of class A (required by spec.), what works better?
A a; // is the constructor even called here?
or
A* pa; // and allocate later a new instance
Thanks in advance
"A a; - is the constructor even called here?" - yes, the constructor is called.
"* pa; - and allocate later a new instance" - if you actually assign something to this pointer variable before using it, then it can work. But do you?
In general I'd say that the need for global variables indicate a flaw in the design. But if you really have to have them, then make sure they are constructed before you use them.
If A a is used, there would not be a need to release memory allocated to a. When the main() function exits, the destructor for A will be automatically called.
If A *pa is used, ideally pa should be explicitly deleted at some point in the code with delete pa and care should be taken to not use pa after it has been deleted.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In Win32 Console Application (Visual C++) I have a array of objects and each object contains some other objects and variables, ex. (Owner and Equipment are structs, TimeInfo is class):
class Order
{
public:
Order();
~Order();
Owner owner;
Equipment equipment;
char *problem;
TimeInfo timeinfo;
void write();
int order_number;
};
Next I have class OrderManager, that contains the array of this object:
items = (Order*)(malloc(100 * sizeof(Order)));
In program, I add and remove items, but what is the best way to free memory at the end of program? I have free(manager.items);, but this doesn't work.
As people have already pointed out, you should avoid using malloc in this situation. If you want to allocate 100 instances of Order, you could try something like this:
Order* items = new Order[100];
In this case the default constructor of Order is called for every instance.
When you want to free up the memory, you do:
delete[] items; // note the "[]"
Presumably, you want to handle the Orders within an OrderManager, so a typical place for the new/delete would be in the construtor/destructor of the OrderManager.
When using new and delete, the con- and destructors will be called.
It is important that the con- and destructors are called, since they are typically used to set up and initialize things on construction and release things on destruction.
With malloc and free, all that happens is the allocation of memory on the heap.
In your question you mentioned that
free(manager.items);
does not work. Shouldn't you be freeing the pointer items in stead of manager.items?
I would use a destructor to manage freeing memory allocated in the OrderManager class.
You should be using C++ new and delete to allocate/deallocate memory and also should be using containers to store collections of an object.
Refer to this link for a list of options on how you can initialize the vector:
https://stackoverflow.com/a/6143009/3817744
class OrderManager {
private:
std::vector<Order> items;
public:
OrderManager() {
// Refer to the link above
}
~OrderManager() {
items.clear();
}
}
Here is a link to an interesting post about C++'s new operator by David Mazières. http://www.scs.stanford.edu/~dm/home/papers/c++-new.html