Does new in C++ call a constructor behind the scenes? Or is it the other way around?
I have seen code like new MyClass(*this) which confuses me, since I didn't know that new could take arguments.
Maybe that's because new can call a constructor and, as a result, it can take the arguments declared by a constructor?
MyClass(*this) creates an object of type MyClass by calling its constructor and passing *this as an argument. Putting new behind it means the object is allocated on the heap instead of the stack. It's not new which is taking the argument, it's MyClass.
There is a difference between new and operator new.
The new operator uses a hidden operator new function to allocate memory and then it also "value-initializes" the object by calling its constructor with the parameters after the class name.
In your case you call new which allocates memory using ::operator new() and then it initializes an object of MyClass class in that memory using a constructor with the parameter *this.
#include <iostream>
class A {
public:
int m_value;
A(int value): m_value(value){};
};
int main (){
int *a = new int;
auto b= new A(1);
std::cout << *a << std::endl;
std::cout << b->m_value << std::endl;
printf("%02x ", *b);
}
Program returned:
0
15
0f
As you can see, the new for the a variable creates only a pointer that is value-initialized to 0. That's why when we dereference it we have 0 (all bit all 0, int is 4 bytes most of the time and the pointer point to a memory content = to 0x0000)
But for the b variable we pass parameters. And if we look at the memory content of the b object we can read 0f which means it contains 15 (the member value)
This is not new taking arguments, it's the constructor taking arguments.
Related
I have a Double free or corruption (fasttop) error on this code.
I think i missed something on the "copy constructor".
class Vector{
int taille;
int* ptr;
public:
Vector():taille(0), ptr(NULL){
...
}
Vector(int n){
...
}
//The most important one
Vector(const Vector& source){
if(source.ptr != NULL){
taille = source.taille;
ptr = new int[taille];
for(int i=0;i<taille;i++) ptr[i]=source.ptr[i];
}else{
taille=0;
ptr=NULL;
}
cout << "Copy constructor" << endl;
}
~Vector(){
if(ptr!=NULL) delete ptr;
}
};
And here's the test :
int main()
{
Vector b(5);
Vector a(b);
a=Vector(12);
return 0;
}
The above = operator does not call the copy constructor. Why ?
It says : "double free or corruption (fasttop)"
With the expression
a = Vector(12)
a few things are happening:
First a new temporary Vector object is created (from Vector(12)). This is constructed using the Vector(int) constructor.
The temporary object is assigned to a, using a.operator=(<temporary object>).
The default compiler-generated operator= function does a simple member-wise assignment, i.e. it basically does ptr = other.ptr. This means you now have two objects ptr members pointing to the same memory: The temporary object, and a.
The temporary object is destructed once the assignment is made. This means the memory occupied by that object is passed to delete (which really should be delete[]).
This of course means that a.ptr is no longer pointing to valid memory, and when it later goes out of scope and is destructed you try to delete the already deleted memory.
There is no copy-construction going on here. It's all copy-assignment. Copy construction is only used on actual construction, when an object is created (temporary or not). I think you're confused because the = symbol can be used for copy-construction, as in
Vector a = b; // This is a copy-construction
// The copy-constructor of `a` is called with
// a reference to `b` as argument
// It's equal to `Vector a(b)`
This is very different from assignment
a = b; // This is a plain assignment
// It is equal to `a.operator=(b)`
The crash is solved by following one of the rules of three, five or zero.
I also recommend you read e.g. this canonical assignment operator reference.
You are creating a temporary Vector in the assignment a = Vector(12), which is being assigned via operator= to a. The temporary Vector gets destroyed at the end of the assignment statement, and a gets destroyed at the end of the function. Both point at the same allocated array because you did not define a copy-assignment operator=:
http://www.cplusplus.com/doc/tutorial/operators/
Can anyone explain the meaning of *p=*q in this C++ code? Is this a copy constructor concept?
class A{
//any code
}
int main(){
A *p=new A();
A *q=new A();
*p=*q;
return 0;
}
Is this a copy constructor concept?
No, what you are referring to is a copy assignment concept. Consider this:
int* p = new int{9};
int* q = new int{10};
*p = *q;
As you can see above, only the value of the variable q which is pointed to is copied. This is the equivalent of the copy assignment for objects. If you were to do this:
p = q;
Then this would not be a copy assignment, because both int's point to the same address and value, meaning any change to p or q would be reflected on the other variable.
To give a more concrete and validated example, here is some code:
int main()
{
int* p = new int{9};
int* q = new int{10};
*p = *q;
//p = 10, q = 10
*p = 11;
//p = 11, q = 10
delete p;
delete q;
}
And here is a supplementary counter-example
int main()
{
int* p = new int{9};
int* q = new int{10};
p = q;
//p = 10, q = 10
*p = 11;
//p = 11, q = 11
delete p;
//delete q; Not needed because p and q point to same int
}
As you can see, the changes are reflected on both variables for p=q
Side Note
You mentioned copy-construction, but you were unclear about the concept. Here is what copy-construction would have looked like:
int* p = new int{9};
int* q = new int{*p}; //q=9
Copy construction differs from copy assignment in the sense that with copy construction, the variable doesn't already have a value, and for an object, the constructor has yet to be called. Mixing up the 2 terms is common, but the fundamental differences make the two concepts, well, different.
It looks like, you're unclear about the copy constructor and copy assignment. Let's first have a look at both concepts individually, and then I'll come to your question. The answer is a little long, so be patient :)
Copy Constructor
Here, I'm not going to explain how to write a copy constructor, but when the copy constructor is called and when it's not. (If you want to know, how to write a copy constructor, see this)
A copy constructor is a special constructor for creating a new object as a copy of an existing object. (It is called whenever there's a need for making a copy of an existing object)
These are the scenarios when the copy constructor will be called to make the copy of an existing object:
Initializing an object with some previously created object:
SomeClass obj;
// ...
SomeClass anotherObj = obj; // here copy constructor will be called.
See, SomeClass obj; statement is simply creating an object (here, default constructor will be called to create the object). The second statement SomeClass anotherObj = obj; is instantiating an object, initialized with the values of obj (an existing object), so copy constructor will be called here. You can also initialize an object with an existing object this way: SomeClass anotherObj(obj); (This statement is equivalent to SomeClass anotherObj = obj;)
Except:
If you initialize with some rvalue expression. e.g.
SomeClass someObject = aObject + anotherObject;
In this case, move constructor will be called. See, What are move semantics?
Passing an object by value to some function (see Passing arguments by value):
See, the following code snippet, here the function doSomething is accepting an object as parameter by value:
void doSomething(SomeClass someObject)
{
// ...
}
There are some cases, when there will be a need to make the copy of the passed argument in the parameter object someObject, I've listed when there will be a need to make the copy and when there'll not be a need.
Have a look at the following code snippet:
SomeClass someObject;
// ...
doSomething(someObject); // here copy constructor will be called.
The statement SomeClass someObject; is just instantiating someObject by calling the default constructor.
The second statement doSomething(someObject); is calling the function doSomething previously shown, by passing someObject as argument. This is the case, when there's a need to make a copy of someObject to pass to the function.
Except:
Similiary, If we call doSomething with some rvalue expression, it will call move constructor instead of copy constructor.
Returning an object from a function by value:
Let's have a look at the following definition of doSomething
SomeClass doSomehing()
{
SomeClass someObject;
// ...
return someObject;
}
In the above function doSomething, an object of SomeClass is being created and after doing some task, the object is being returned by the function, in this case, a copy of the someObject will be created and returned.
Except:
Similiary, If doSomething returns some rvalue expression, it will call move constructor instead of copy constructor.
Copy Assignment
Copy Assignment is usually confused with the copy construction, let's have a look at how it is different than the copy construction:
SomeClass someObject;
// ...
SomeClass anotherObject;
// ...
anotherObject = someObject; // here copy assignment operator will be called.
The first two statements are just creating someObject and anotherObject, you see, the third statement is actually calling the copy assignment operator and not the copy constructor.
Constructors are only called when some new object is being created. And in the case of anotherObject = someObject;, both the objects are already created, so there won't be any call to the copy constructor. Instead a copy assignment operator will be called (to see, how to overload a copy assignment operator, see this)
Now, let's have a look at your code snippet:
A *p=new A();
A *q=new A();
*p=*q;
In the first statement A *p=new A();, default constructor will be called to create an object (in this case, new object will be created on heap) and p will be initialized with the address of the newly created object (as p is a pointer)
Similar is the case with second statement A *q=new A(); (It is creating another object and q will be initialized with newly created object)
Now, the third statement: *p = *q; (here * is Dereference operator)
To understand, what the third statement is doing, let's have a look at some pointers and de-referencing them to get the actual object, which they're pointing to.
int someVariable = 5;
int *somePointer = &someVariable;
// ...
*somePointer = 7;
Let's try to understand the above code snippet: someVariable is created and initialized with a value of 5, then somePointer is created and initialized with the address of someVariable.
Now, the last statement *somePointer = 7;, it is actually de-referencing the somePointer and by de-referencing, it'll get the the variable which it is pointing to. (so it will get someVariable) and then it is assigning 7 to it. So after this statement, someVariable's value will become 7
Let's have another example:
int* somePointer = new int;
int* anotherPointer = new int;
// ...
*somePointer = 5;
*anotherPointer = 7;
// ...
*somePointer = *anotherPointer;
First, somePointer will be created and initialized with the address of dynamically allocated int variable (will be allocated in heap, see Dynamic Allocation in c++), similarly, anotherPointer will be initialized with the address of another dynamically allocated variable.
Then, it is assigning 5 to the first variable (which is being pointed by somePointer) and 7 to the second variable (which is being pointed by anotherPointer)
Now, the last statement will be of your interest, *somePointer = *anotherPointer;, in this statement *somePointer is de-referencing and getting the first variable (whose value was 5) and *anotherPointer is de-referencing and getting the second variable (whose value is 7), and it is assigning the second variable to the first variable, resulting in changing the first variable's value to 7.
Now, let's have a look at your *p=*q; statement, (p was pointing to the first object of A, and q was pointing to the second object of A, both dynamically allocated), *p will dereference p and get the first object, *q will dereference q and get the second object, and then the second object will be copied in the first object, and if you see, no new object is being created in *p=*q;, and only the value of second object is being created in the first object, so copy assignment operator will be called here and no the copy constructor.
Another thing
You should de-allocate the dynamically allocated memory which you borrowed using new operator:
delete p;
delete q;
You should add these two lines at the end of your program, so to avoid Memory Leak.
As stated in the comments, one need to understand the basics first:
With A *p=new A(); one gets a pointer to a memory region on the heap in which an object of type A is constructed.
With *p one dereferences the pointer, i.e. one retrieves the object.
Now *p = *q uses the (possibly implicitly declared) assignment operator of class A in order to give *p -- the object pointed to by p -- the value of *q. This operation could equivalently be written as p->operator=(*q).
The last step, the assignment, is identical to what you would obtain with objects instead of pointers (which is usually a better way to go in C++ and often called RAII):
A r;
A s;
r=s;
I'm looking at the following code:
// operator new example
#include <iostream> // std::cout
#include <new> // ::operator new
struct MyClass {
int data[100];
int kk;
MyClass(int ea) : kk(ea) {std::cout << "constructed [" << this << "]\n";}
};
int main () {
std::cout << "1: ";
MyClass * p1 = new MyClass(1);
// allocates memory by calling: operator new (sizeof(MyClass))
// and then constructs an object at the newly allocated space
std::cout << "2: ";
MyClass * p2 = new (std::nothrow) MyClass(2);
// allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
// and then constructs an object at the newly allocated space
std::cout << "3: ";
new (p2) MyClass(3);
// does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
// but constructs an object at p2
// Notice though that calling this function directly does not construct an object:
std::cout << "4: ";
MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
// allocates memory by calling: operator new (sizeof(MyClass))
// but does not call MyClass's constructor
delete p1;
delete p2;
delete p3;
return 0;
}
And I have two questions:
Is the object 2 destroyed when executing the line
new (p2) MyClass(3);
that should construct the object 3 in the object 2's allocated space?
The line
MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
also works without the ::, what's the purpose of the scope resolution operator used without a class/namespace before it?
Firstly, no, the second object's destructor is not called. A new object is just initialized in its place. If you like, you can explicitly call the destructor of the object with p2->~MyClass(); before you reuse its memory.
Secondly, the purpose of using :: to qualify the allocation function is to make sure it comes from the global namespace. The standard implicitly defines two overloads of operator new for all translation units, and if you include <new>, you get a few extras. All of these are defined in the global namespace (not in std). It's possible to overload operator new for classes (simply provide them as member functions), so qualifying with :: makes sure the global version is used instead.
Answer1: The object located at p2's lifetime ends when you reuse it's memory for a new object. It won't have its destructor run so it's not "destroyed" cleanly, although with only POD members and no user-declared destructor, in this case it makes no difference.
Answer2: Using :: forces the lookup for operator new to only consider operator new declared at global scope. In the scope which you are calling operator new, there is no other operator new that would be considered in any case, so it makes no difference.
A copy constructor is used for many things such as when I need to use pointers or dynamically allocate memory for an object. But looking at this example at tutorialpoint.com:
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
// Member functions definitions including constructor
Line::Line(int len)
{
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}
Line::Line(const Line &obj)
{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}
void display(Line obj)
{
cout << "Length of line : " << obj.getLength() <<endl;
}
// Main function for the program
int main( )
{
Line line(10);
display(line);
return 0;
}
the result is :
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
and when I commented out (the copy constructor) and the code inside destructor I got the same results:
Normal constructor allocating ptr
Length of line : 10
So what is the difference between using the copy constructor here or not? Also why does "Freeing Memory!" occur twice?
The argument to the display() function is passed by value, so the compiler calls the copy constructor to create it. When the class defines its copy constructor you get the correct semantics: the copy constructor makes a copy, and that copy has its own memory to hold the length. When you remove the copy constructor, the compiler generates one for you, and the copy that gets passed to display() has the same pointer as the original. When that copy gets destroyed it deletes the memory that ptr points to. When the original gets destroyed it deletes the same memory again (which happens to have no visible effects here). That's definitely not what you want to have happen, which is why you need to define a copy constructor. As #Joe says: inside the destructor, print the value of `ptr' to see this more clearly.
Print the address of the memory being freed.
I believe you will find the compiler generated the constructor for you, did a value copy of the contents, including the pointer, and you are double-freeing the pointer and just getting lucky that the runtime isn't complaining about it.
The compiler generated copy constructor is still being called - nothing has changed in that regard, you just aren't printing anything from it since you didn't write it.
If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member wise copy between objects. The compiler created copy constructor works fine in general. We need to define our own copy constructor only if an object has pointers or any run time allocation of resource like file handle, a network connection..
A constructor of some type T of the form
T (const & T);
The single argument must be a const reference to an existing object of same type
Creates a duplicate of the existing object
Used whenever a copy of an object is needed
Including arguments to functions, results returned from functions
Problems with pointer-based arrays in C++:–
No range checking.
Cannot be compared meaningfully with ==
No array assignment (array names are const pointers).
If array passed to a function, size must be passed as a separate argument.
here is my c++ code :
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
}
it returns me the output like :
Say i am in someFunc
Null pointer assignment(Run-time error)
here As the object is passed by value to SomeFunc the destructor of the object is called when the control returns from the function
should i right ? if yes then why it is happening ? and whats the solution for this ???
Sample is passed by value to SomeFunc, which means a copy is made. The copy has the same ptr, so when that copy is destroyed when SomeFunc returns, ptr is deleted for both objects. Then when you call PrintVal() in main you dereference this invalid pointer. This is undefined behavior. Even if that works then when s1 is destroyed ptr is deleted again, which is also UB.
Also, if the compiler fails to elide the copy in Sample s1= 10; then s1 won't even be valid to begin with, because when the temporary is destroyed the pointer will be deleted. Most compilers do avoid this copy though.
You need to either implement copying correctly or disallow copying. The default copy-ctor is not correct for this type. I would recommend either making this type a value type (which holds its members directly rather than by pointer) so that the default copy-ctor works, or use a smart pointer to hold the reference so that it can manage the by-reference resources for you and the default copy-ctor will still work.
One of the things I really like about C++ is that it's really friendly toward using value types everywhere, and if you need a reference type you can just wrap any value type up in a smart pointer. I think this is much nicer than other languages that have primitive types with value semantics but then user defined types have reference semantics by default.
You usually need to obey the Rule of Three since you have an pointer member.
In your code example to avoid the Undefined Behavior you are seeing:
Replace the need to in first statement by must.
Since SomeFunc() takes its argument by value, the Sample object that you pass to it is copied. When SomeFunc() returns, the temporary copy is destroyed.
Since Sample has no copy constructor defined, its compiler-generated copy constructor simply copies the pointer value, so both Sample instances point to the same int. When one Sample (the temporary copy) is destroyed, that int is deleted, and then when the second Sample (the original) is destroyed, it tries to delete the same int again. That's why your program crashes.
You can change SomeFunc() to take a reference instead, avoiding the temporary copy:
void someFunc(Sample const &x)
and/or you can define a copy constructor for Sample which allocates a new int rather than just copying the pointer to the existing one.
When you pass the argument for the function it's called the copy constructor, but you don't have one so the pointer is not initialised. When it exits the function, the object is calls the destructor to delete the unitialised pointer, so it thows an error.
Instead of
int main()
{
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
}
try to use
int main()
{
Sample* s1= new Sample(10);
SomeFunc(*s1);
s1->PrintVal();
}