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
comming from other programming language why can't I do this in c++:
myClass mc = new myClass();
it seems that it suffices to just write:
myClass mc;
but then what if I want to use make mc be a new instance of myClass and dump the existing one?
comming from other programming language why can't I do this in c++:
Because in C++ to initilize variable types on the left and right side of = must be compatible. In your case:
myClass mc = new myClass();
mc has type myClass and expression on the right has type myClass *. So you either need to change left side to:
myClass *mc = new myClass();
or right side to:
myClass mc = myClass();
to make both sides compatible. What implications it would have on class instance lifetime you should get from a C++ textbook.
new generates the object using dynamic memory from the heap. Your second line allocates it on the stack or in the data section. Please read about the differences of stack, heap and data section and the consequences for your application!
The new keyword means allocating heap memory to a pointer
int* pointer = new int(5);
This means that the int will be allocated on the heap as opposed to the stack.
When allocating memory with the new keyword you also have to delete it
delete pointer;
In your case, you should be able to assign a new value like so
mc = myClass();
without the new keyword.
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 5 years ago.
Improve this question
Let's say I have an array a which holds pointers to objects of a class B. Let's say a[0] points to object c.
If I now set a[0] = nullptr, will the destructor of c be called and thus c destroyed if c was constructed on the stack and if a[0] was the only thing referencing c.
If you refer to regular pointers (Obj* ptr) so c's d'tor would not be called because of the assignment. It might be called if there's a code like -
... // Some code and initialization before
{
Obj c;
a[0] = &c;
a[0] = NULL; //c isn't affected in any way by this assignment
} //End of scope. **c's d'tor is called here**
Although, if c was allocated on the heap, it's memory would have leaked
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 know if I create a pointer in the header file, I should always delete it when the destructor is being called, but what about if I create a pointer inside of a function. I know basic variables get destroyed at the end of the block, is it the same for pointers?
For example:
Class::Function()
{
int i = 3; // This gets destroyed after the function ends
int* j = 5; // What about this? Do I have to delete it somewhere to keep from a leak?
}
If I initialize j inside of the constructor, I would say delete j; to prevent leaks, etc. Is there something I should do in this case?
Assigning int value to pointer
int* j = 5;
is illegal because you are storing int to int*. Anyway you can cast it
int* j = reinterpret_cast<int*>( 5 );
but dereferencing this pointer would lead to undefined behavior, since you dont know where does that pointer point.
You should init pointers like that
int* j = nullptr;
Since c++11 you cant create instance of nullptr_t and assign it.
nullptr_t initPointer;
int* j = initPointer;
If you dont use new operator to assign memory to pointer, you can't delete this pointer, it would lead to undefined behavior. Otherwise if you use new you need matching delete or you would get memory leak. If you want to check your program have memory leaks, check this thread and choose one tool. I can recommend valgrind.
Every call to new needs a matching call to delete. If you have more new's than delete's, you get memory leaks. If the opposite, you get double deletes. In your case, if you never called new, then there's no need for delete!
There are tools out there to help match your new's and deletes. My personal favorite is cppcheck. It's super quick and easy to use, and it runs on the c++ source code! It generally does a good job at catching unmatched new and delete calls.
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
Consider the following code:
struct A {
int someInt;
};
A *a = new A;
A *b;
delete a; // ok
delete b; // crash
It crashes, but I don't know why. I thought deleting null pointers is a no-op.
Do I even need to delete structs? Is it bad practice to create structs on the heap? Is it better to create them on the stack?
Deleting null pointers is a no-op, yes, so if b were a null pointer then you'd be fine.
But it's not. It's an uninitialised variable with an indeterminate value.
Here's a null pointer:
A* b = nullptr;
(If you write A* b; at global scope, or if you write static A* b; in a function, or if you are defining a static class member, then b has static storage duration and is automatically zero-initialised for you; this is the one exception to the rule.)
And, yes, you should avoid dynamic allocation where possible — using it for no good reason complicates your code for, well, for no good reason.
b is a uninitialized pointer. There is nothing to delete.
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
Consider the following code:
int cnt = 10;
Object* objects = new Object[cnt];
for(int i = 0; i < cnt; i++) {
*(objects + i) = Object();
}
//All objects are destroyed here!
All objects are destroyed when the program exits the loop. I think it's because they go out of scope (When I debug it, the destructor of each object is called). How do I store them on the heap but still reference them from the pointer? Why is the following not allowed?
*(objects + i) = new Object(); //not allowed by compiler
UPDATE:
It seems that only the temporary objects are being destroyed. I was looking for a way to store these temporary objects on the heap (So that they are not temporary) but that would create a memory leak. The confusion came from the fact that I didn't know that an array of objects is automatically initialized on creation (I came from C#).
Also, what happens when I call delete[] objects? From what I've read, only the pointer is actually deleted. Does that mean I have to cycle through each object and manually delete it? If the object itself also stores other objects (on the heap), do I have to destroy those objects in its destructor method? (Which will automatically be called when I use destroy object).
When you execute *(objects + i) = Object(), a temporary Object instance is created on the stack and passed to the assignment-operator of class Object, with this being objects+i.
If no assignment-operator is defined, then the default assignment-operator is invoked.
The default assignment-operator simply copies each one of the member fields of the input object into the corresponding member field of this (in a manner similar to that of a structure-assignment operation).
So the comment //All objects are destroyed here! is wrong.
When you execute Object* objects = new Object[cnt], an array of Object instances is created, and the default (empty) constructor is invoked for each one of them.
So the loop which executes *(objects + i) = Object() for each instance is completely redundant here, because you are essentially creating an Object instance using the default (empty) constructor and then passing it to the assignment-operator, for each instance in the array.
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
suppose for example this struct :
struct Point{
int x;
int y;
};
and I declared a pointer to this struct:
Point* p;
where're x and y of that p, heap or stack?
and Is that the same for classes?
where're x and y of that p, heap or stack?
Nowhere. You haven't created an object, just a pointer that could point to one.
If you create an automatic object on the stack, then that's where it will be:
Point point;
Point * p = &point;
If you create a dynamic object on the heap (officially called the free store), then that's where it will be:
Point * p = new Point; // Don't forget to delete it.
Is that the same for classes?
Yes; a struct is a class.
The answer to the question depends on what p points to. If it points to a stack-allocated structures, then p->x and p->y are on the stack. If it was obtained with new (or malloc), then they are on the heap.
Unlike some other languages, there is no difference in layout of C++ classes and structs. The difference between them is only in in default access restrictions: class members are private by default, while struct members are public.
It depends on how you initialize p. The variables x and y are in whatever p points to: if that is on the heap, they are on the heap; if it is on the stack, they are on the stack, and if p points to a static variable, they are neither.
Forget about heap and stack: those are implementation details for the compiler. What you're interested in is not where the bits are located, but the lifetime they might have.
And C++ doesn't really have structs: regardless of the keyword used (struct, class or union), what is declared is a class type. (Class types can be divided into two large categories, unions and non-union class types.)