Storing instance on heap and referencing it from a pointer [closed] - c++

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.

Related

What happens when you use "new" twice on the same object? [duplicate]

This question already has answers here:
Why should C++ programmers minimize use of 'new'?
(19 answers)
Closed 5 years ago.
Lets say we have this..
class MyClass
{
int value;
void addIntToObject(int num)
{
value = num;
}
}
MyClass *object = new MyClass();
object->addIntToObject(1);
object->addIntToObject(2);
Now let's say we do this again...
object = new MyClass();
By using new twice on the same object, does that mean we have deleted all data that was stored in object? can someone explain to me the exact workings of using new twice on the same object
Would this be an efficient way to free memory? (like using delete and delete[])
You didn't "do new twice on the same object". The new expression creates an object. By doing new twice you made two entirely separate objects.
The variable object is a pointer. It points to other objects. The = operator on a pointer means to change which object the pointer is pointing to.
So in your code there are two objects, and you change object (the pointer) to point to the second object. The first object still exists but nobody knows where it is, this is known as a memory leak.
The thing on left side of = is a pointer i.e to be simple it can contain adrress of some memory location/object instance
When you do new MyClass() -> each execution of this statement will produce a new instance/object/memory of MyClass
So when you do this first time,
MyClass *object1 = new MyClass();
// here object1 now holds the address of object
created by executing 'new MyClass()' suppose that address is 1
Now create a object again,
object1 = new MyClass();
//here object1 now holds the address of object
created by again executing 'new MyClass()' suppose that address is 2
In the end both objects remain in memory i.e 1 as well 2. So nothing is deleted.
The pointer(left side of =) was first pointing to object with adrress 1. Now, it pointing to object with adress 2.

c++ pointer deletion inside function [closed]

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.

why newly instance(object) is created when constructor exits? [closed]

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 was asked in an interview why a new object is created when the constructor exits?
I said that when we declare object for any class, memory is created in stack or heap at run time. As soon as memory is created, the constructor is called, and when it finishes, it returns the new object because the space is filled with the contents of constructor initialization and thus the new object.
I would be heartily thankful if some one explain maybe what the interviewer was asking for?
The correct answer to that interview question is that a constructor doesn't return anything.
A class' constructor is called when an object of its type is initialized. At that point the memory region to construct the object in is already reserved and the address known. There's therefore no need for the constructor to return anything unless there's an error condition, which can be reported through an exception.
The constructor's only job is to write useful values to that memory region and usually establish an invariant of the class that is maintained by copy and move operations.
To do its job a constructor will at first call its parent's constructor, which in turn will call its parent constructor, up to the top of the inheritance hierarchy. In case of multiple inheritance, the parent constructors are called in the order of their declaration. For virtual inheritance the constructor of the virtual class will be called first to ensure that it's properly initialized wherever it's used within the class hierarchy.
Once the parent constructors finished, the class' members are initialized in the order of declaration and finally the constructor's own body is executed.
Destruction is done in reverse order and only what's completely constructed is destroyed.
An object is completely constructed, once its constructor finishes.
Therefore if a member or parent constructor throws, or if you throw an exception in the constructor's body, all members and parents that were successfully created up to that point will be properly destroyed in the reverse order of their construction.
In case of allocation using new, the memory for the object will be freed and the exception re-thrown.
As you can see a constructor just initializes the memory of an object about which you already know how to access it (usually through a variable) and therefore it never returns any value.
To add an example:
class T : private parent {
U member_first;
V member_second;
};
T foobar() {
T a{};
return a;
}
This will explicitly construct an object of type T using the default constructor.
The function within which the variable a is defined will have sizeof(T) bytes reserved on the stack (Assuming the machine has a stack ;) ) when it is invoked. So far no constructors were invoked.
Now when the default constructor gets called, the this pointer for the object named a is set to the value of &a and a constructor default-defined like this is executed:
T::T() : parent{}, member_first{}, member_second{} {}
I hope this example makes it clear, that rather than having the constructor return something, it is implicitly given the address of the memory area that has to be initialized, similarly like a function returning void, that takes a pointer as an argument and changes the value pointed to.
The new object (a reference to the created object) is returned that you
can copy and assign it to other object
can apply other methods of the class to the created object.
Shortly speaking that you could create temporary objects used in expressions.
Consider an example
#include <iostream>
#include <string>
int main()
{
std::cout << std::string( "Hello ").append( "World!" ) << std::endl;
return 0;
}
A constructor call is an expression and it has type distinct from void.

Local variable deletes memory of another variable when going out of scope [duplicate]

This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 9 years ago.
While designing a class that dynamically allocates memory I ran into the following problem regarding memory allocation. I was hoping that some of you might be able to point me in the right direction as to how I should design my class in a better way. My class dynamically allocates memory and therefore also deletes it in its destructor.
In order to illustrate the problem, consider the following silly class declaration:
class testClass{
int* data;
public:
testClass(){
data = new int;
*data = 5;
}
~testClass(){
delete data;
}
};
So far so good. Now suppose that I create one of these objects in main
int main(){
testClass myObject;
return 0;
}
Still no issues of course. However, suppose that I now write a function that takes a testClass object as an input and call this from main.
void doNoting(testClass copyOfMyObject){
//do nothing
}
int main(){
testClass myObject;
doNothing(myObject);
return 0;
}
This time around, the function creates a local variable, copyOfMyObject, that's simply a copy of myObject. Then when the end of that function is reached, that local object automatically has its destructor called which deletes the memory pointed to by its data pointer. However, since this is the same memory pointed to by myObject's data pointer, myObject inadvertently has its memory deleted in the process. My question is: what is a better way to design my class?
When you call doNothing(), it is making a copy of your testClass object, because it is being passed by value. Unfortunately, when this copy is destroyed, it calls the destructor, which deletes the same data used by the original instance of testClass.
You want to learn about "copy constructors", and "passing by reference". That is, you should define a copy constructor for your class so that when a copy is made of an instance, it allocates its own memory for its data member. Also, rather than passing by value, you could pass a pointer or a reference to doNothing(), so that no copy is made.
You should create a copy constructor, that is a constructor of the form:
testClass::testClass(const testClass &o)
{
// appropriate initialization here
}
In your case, "appropriate initialization" might mean allocate a new chunk of memory and copy the memory from the old chunk into the new chunk. Or it may mean doing reference counting. Or whatever.
You should also read more about the Rule of Three right here on StackOverflow!
Here's a guideline from an authority: A class with any of {destructor, assignment operator, copy constructor} generally needs all 3
You need a copy constructor that will make a new allocated int for your data, that will then destruct that, but not affect the original.
Alternately, you can make a private copy constructor that's blank, which effectively disables it, forcing your users to pass by reference, or another non-copying way of doing things.

Is object created without new operator deleted in a specific case in C++

If we have the following code snippet:
MyObject my_object = MyObject(0);
my_object = MyObject(1);
What happens to MyObject(0)? Is it deleted? Looking at what I have read about it it should only be deleted when we leave the scope of creation, so the anwser is probably no. If this is the case is there any way to explicitly delete it other than using pointers?
MyObject my_object = MyObject(0);
This line creates my_object on the stack using MyObject's constructor that can accept an int.
my_object = MyObject(1);
This line creates a temporary MyObject, again, using the same constructor as the first. This is then assigned to my_object by calling the assignment operator. If you didn't provide this operator then the compiler will make one for you that performs a shallow copy. When this statement completes, the temporary MyObject goes out of scope and the destructor for it is called.
When your my_object goes out of scope it is in turn destroyed in the same fashion. At no point do you need to manually delete this because everything is allocated on the stack.
There are two main regions in memory when talking about newly created objects: the stack and the heap. The heap contains all objects created dynamically with new. These objects need to be explicitly deleted with the delete operator. The stack is scope-specific and all objects defined on the stack will be deleted automatically. Since you don't use new, all your objects will be destroyed when their scope ends.
Assuming no compiler optimizations, your code roughly translates to:
{
MyObject my_object;
MyObject tempObject0(0);
my_Object = tempObject0;
MyObject tempObject1(1);
my_Object = tempObject;
}//3 objects are deleted by this point (in theory)
Also note the difference between
MyObject myObject(0);
and
MyObject myObject = MyObject(0);
The second case creates a temporary object, so it will be less efficient. This all of course assuming no optimizations. Depending on the compiler, it might translate to the same thing.
The term delete has a special meaning in C++, so the use of deleted is unfortunate.
MyObject my_object = MyObject(0);
This line declares that an object of type MyObject created with automatic storage duration (ie, on the stack). This object will be destructed (ie, its destructor will be executed) when the scope ends. No provision is made in the Standard for the recollection of the associated memory (see later example).
This object of type MyObject will be constructed using the expression MyObject(0). This constructor will initialize the memory that has been set apart for its exclusive use.
Note: actually, a temporary could be created and the copy constructor then called, but most compiler eschew this intermediate step, thankfully, as the Standard specifically allows it.
my_object = MyObject(1);
This line assigns a new value, determined by the expression MyObject(1), to the already existing my_object object. To do so, a temporary of type MyObject is created with automatic storage duration. Then, the assignment operator is executed; if not overloaded it will copy the state of the temporary into my_object, erasing what previous state was there. At the end of the expression, the temporary is destructed (once again, no provising is made for the recollection of the associated memory).
Note: MyObject(0) is not "deleted", as it does not exist, instead the memory it had written its state to is reused to copy the state from MyObject(1).
As promised, since this seems your worry, a discussion on the memory aspects. This is compiler specific, but most compilers do behave similarly.
Suppose that we have the following function:
void f() {
MyObject my_object = MyObject(0);
{
my_object = MyObject(1);
do_something(my_object);
}
{
my_object = MyObject(2);
do_something(my_object);
}
}
How much space does it require on the stack ?
We assume that it performs direct construction on the first line
We assume the compiler not smart enough to perform Stack Coloring (Clang does not, for example)
With those assumption, it requires the space for 3 MyObject.
MyObject my_object = MyObject(0);: my_object need live until the end of the function
my_object = MyObject(1);: a temporary need be created
my_object = MyObject(2);: a temporary need be created
The stack space is recollected at the end of the function execution.
If the compiler was smart enough to perform Stack Coloring, then the two temporaries (that are never needed together) could use the same memory spot, thus lowering the space requirement to 2 MyObject.
A smart optimizer could also, possibly, directly build MyObject(1) and MyObject(2) directly into my_object (if it can prove that the effects would be the same than building a temporary and then copying it), thus lowering the space requirement to 1 MyObject.
Finally, if the definition of do_something is visible, and it does not use its parameter, then under certain conditions it could (in theory) completely bypass the construction of my_object. Such optimizations can be witness with simple programs like:
int main() { int i = 0; for (; i < 1000; ++i); return i; }
which are trivially optimized to:
int main() { return 1000; }
(Note how i disappeared)
As you may notice... it's actually very hard to guess what the compiler/optimizer will be able to do. If you really have tight memory requirements, then (perhaps surprisingly), your best bet might be to replace the blocks by functions.
1st line is creating an temp object and this object is assigned to my_object.
In 2nd line, a temporary object is created and it is assigned to my_object.
So there is only one object my_object
We need not to think about temporay object. It is compiler responsibility to handle temporary object.