Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
For deleting and an array of element we use delete[].
Is it possible to delete the pointers the way I am doing below?
ClassA* object = new ClassA();
ClassA* pointer1 = object;
ClassA* object2 = new ClassA();
ClassA* pointer2 = object2;
delete pointer1,pointer2;
Why its not possible to use delete this way?
[Edit]
Can I put it like, what are the drawbacks due to which the above delete has not been implemented?
It's not possible, because there is no provision for it in the C++ language definition. I'm not sure there is any "good" answer to why the language doesn't support a list of items for delete, except for the fact that it's simpler to not do that.
You need to write one delete for each variable. Of course, if you have many pointerX, then you probably should be using an array instead, and use a loop to delete the objects.
Edit: Of course, if you are calling delete in many places in your code, you are probably doing something wrong - or at least, you are not following the RAII principles very well. It's of course necessary to learn/understand dynamic allocation to have full understanding of the language, but you should really avoid calling both new and delete in your own code - let someone else sort that out (or write classes that do "the right thing")
It is not working this way. delete is a command for a single pointer. You can put the pointers in a structure (e.g. array) or a container (e.g. using a vector container class) and delete for each one of them by iterating the structure/container.
Related
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
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
Is it useful to create a pointer or an array of pointers on the heap ? if so when and why would I need to do so ?
For example:
#include <iostream>
class Box { /* things... */ };
int main(void){
// Single pointer on the heap
Box** pBox = new Box*(nullptr);
*pBox = new Box();
// Array of pointers on the heap
Box** pBoxes = new Box*[3]{};
pBoxes[0] = new Box();
pBoxes[1] = new Box();
pBoxes[2] = new Box();
// Delete pointers...
return 0;
}
EDIT: Just to make my question more clear ... I know dealing with raw pointers is not the best practice ... I just want to fully understand pointers and their uses as they are important part of c++ hence my question is (is it useful...).
The reasoning behind allocating any memory space on the heap or on the stack is not related to the type of variables allocated, it's related to how it's allocated and how it's meant to be used.
In any case, nowadays you should usually avoid new statements and use "managed" pointers, particularly the std::xxx variants.
From what i read, the heap has slower access speed than the stack so, I don't think that it is very useful to do what you are talking about.
Maybe this will help you trought your research: http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html
As another answer mentioned, usually actual access to the heap is slower than access to the stack, however access speed generally isn't the reason for creating and dealing with pointers.
The typical use case for pointers is to avoid copying data. When you're dealing with large objects and passing them between many functions, it is considered "better" to pass by reference rather than by value.
If you use the object from the stack (unless you pass it as a reference, but there are limitations when doing this) it makes a copy of the whole thing for the called method. When passing a pointer to a method, it is only copying an address.
See if this article helps you understand the differences.
Yes, there can be reasons to have pointers on the heap. A factory function that keeps track of every object it creates might store them in a vector, for example:
vector<unique_ptr<Box>> BoxFactory::allBoxes;
Box* BoxFactory::makeBox()
{
allBoxes.emplace_back(make_unique<Box>());
return allBoxes.back().get();
}
Note: some people have suggested that this is not double-indirection. It is:
// Accesses some_box_member of the first Box.
allBoxes.data()->get()->some_box_member
Just as with the OP's example, you have two pointers in play, not just one. The vector contains pointers which have been allocated on the heap, and those pointers contain another pointer that points to the Box object.
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 8 years ago.
Improve this question
I'm trying to make a linked list with a set of data and I'm wondering if there's a way to make a variable's address change. Something like:
for(int i=array.size()-1;i>=0;i--)
{
Node *previous_ptr;
Node *current_ptr = new Node(array[i], previous_ptr);
previous_ptr=current_ptr;
delete current_ptr;
}
So I want current_ptr's address to change (allocate a different spot of memory) so the linked list gets constructed if that's possible. And I can't use alloc for it only new and delete.
Calls of new produce different addresses every time you call it, unless you call delete, in which case the memory becomes reusable, so operator new can return it again.
Your code creates hanging pointers: when you call delete on line 3
Node *current_ptr = new Node(array[i], previous_ptr);
previous_ptr=current_ptr;
delete current_ptr;
the value of current_ptr and previous_ptr immediately become invalid. At the same time, the pointer returned by new becomes eligible for reuse, so you get the same pointer when you call new again.
You should not call delete on anything that you plan to use again.
In addition, previous_ptr declared inside a for loop is not useful, because its value is thrown away on each iteration. If you would like to keep that pointer between iterations, declare it outside the loop.
As far as I know, you cannot change a variables address and it doesn't make any sense to me, if you think about what is happening in the background.
If you need a different address for your data, allocate new memory, store your data a 2nd time and delete the old data.
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 8 years ago.
Improve this question
Hello I have three classes
AbstSoccerTeam
PlayersSoccerTeam
PlayersFieldPlayerStates
PlayerSoccerTeam is a child class of AbstSoccerTeam.
bool AlanSoccerTeam::isClosestTeamMemberToSupportingPlayer(FieldPlayer* plyr)
is a method in player soccer team.
i am trying to call that method in the PlayersFieldPlayerStates class with this
PlayersSoccerTeam* sTeam;
sTeam->isClosestTeamMemberToSupportingPlayer(player);
I can get this problem when i run it
uninitialized local variable 'sTeam' used
I dont know whats going on or why i am getting this error.
Any help is apprecitated greatly
Thanking You
The problem is you have created a pointer to a PlayersSoccerTeam but you have not actually created the object itself yet.
I would suggest doing this.
PlayersSoccerTeam sTeam;
sTeam.isClosestTeamMemberToSupportingPlayer(player);
You could alternatively do this.
PlayersSoccerTeam* sTeam = new PlayersSoccerTeam()
sTeam->isClosestTeamMemberToSupportingPlayer(player);
As perhaps an interesting education experience create a constructor that prints something to stdout when it is run and then try doing these two options and yours to see what happens. A constructor will be run whenever a new object is created.
PlayersSoccerTeam* sTeam;
This line declares a pointer to a PlayersSoccerTeam and nothing else. All you get from this line is a pointer. It doesn't point anywhere in particular since you haven't initialized. There is no PlayersSoccerTeam anywhere to point to.
If you want an object of type PlayersSoccerTeam, then you just want:
PlayersSoccerTeam sTeam;
sTeam.isClosestTeamMemberToSupportingPlayer(player);
Since you told us about your hierarchy, it's possible that you want to use your PlayersSoccerTeam polymorphically as a AbstSoccerTeam. In this case you would need to use either a pointer or reference. This could be done like so:
AbstSoccerTeam* sTeam = new PlayersSoccerTeam();
// ...
delete sTeam;
Note that this still declares just a pointer, but the expression new PlayersSoccerTeam also creates a PlayersSoccerTeam object for the pointer to point to. Note that it's perfectly fine to assign a pointer to a PlayersSoccerTeam to a pointer to its parent AbstSoccerTeam - this is polymorphism in action. If you do this, you must make sure you delete sTeam; later, otherwise the object will be leaked.
A safer way to handle the user of dynamically allocated objects is to use a smart pointer, which you could do like so:
std::unique_ptr<AbstSoccerTeam> sTeam(new PlayersSoccerTeam());
Now you will not have to delete it because the std::unique_ptr takes care of that for you.