What does (X* nptr = new (ptr) X {} ) mean? [duplicate] - c++

This question already has answers here:
What uses are there for "placement new"?
(25 answers)
Two different values at the same memory address
(7 answers)
Closed 19 days ago.
What does (ptr) stands for and why does it change the data stored in ptr?
struct X
{
int a;
int const b;
};
X* ptr = new X{ 1, 2 };
X* nptr = new (ptr) X{ 3, 4 };
And for some reason it doesn't run in any godbolt's compilers but does in visual studio

It requires #include <new> to work. It is an overloaded new operator which calls the constructor without allocating new memory. Instead, the new struct is constructed to memory pointed by ptr and the old data is thus overwritten. See that for reference.

Related

Taking address of an rvalue allowed? [duplicate]

This question already has answers here:
Reference a temporary in msvc
(2 answers)
Closed 5 years ago.
I am practicing things described Here to learn the concept of lvalue and rvalue.
However, when I contrive my own example as follows, I find it compiles and runs without any error (using VS2017). I have learnt that in case 1, it is the same as calling
produceA(10).operator=(A())
and thus is legal. But, I still don't understand why case 2 and 3 are allowed. In fact, case 2 even contradicts the example given in the article. Am I actually getting the addresses of rvalues in these 2 cases? Do they lead to undefined behavior?
#include <string>
class A
{
int data = 1;
public:
A() = default;
A(int in)
: data(in)
{}
A& operator=(const A& rhs)
{
data = rhs.data;
return *this;
}
};
A produceA(int i)
{
A a(i);
return a;
}
int main()
{
// case 1
produceA(10) = A();
// case 2
A* pa = &produceA(10); // rvalue?
// case 3
std::string* pstr = &std::string("Temp"); // rvalue?
return 0;
}
&produceA(10) is the address of the anonymous temporary of type A returned back from the function. You are allowed to set a pointer to it, but that pointer is only valid for the lifetime of the entire statement.
The same can be said for &std::string("Temp"); again, this is an address of an anonymous temporary.

Why my program does not crashes when I assign pointer to NULL? [duplicate]

This question already has answers here:
What will happen when I call a member function on a NULL object pointer? [duplicate]
(6 answers)
Closed 5 years ago.
I've written a very simple code. In created an object dynamically, and then I delete that object and assign it to zero. After that I access a member function of that object, but my program does not crash, instead it returns value.
class MyClass
{
public:
MyClass() {}
int funct() { return 0; }
};
int main()
{
MyClass *mc = new MyClass;
delete mc;
mc = 0;
// The program should crash here as I've set mc to zero after deleting
// it. But it returns the value.
int retVal = mc->funct();
return 0;
}
As per my understanding with new, delete and assignment to zero, this code should crash, or give exception.
You can visualize your method as a function:
int funct(MyClass *this) { return 0; }
You can see that the function doesn't use this at all so it won't crash if it is 0.
However, don't do such things in real code. This is still an Undefined Behavior and compiler optimizations can mess it up.

C++ destruction weirdness [duplicate]

This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 8 years ago.
I am preparing for a C++ test and came across this code example.
In the code example below, obj is passed to SomeFunc. SomeFunc has parameter Foo obj so a copy is made which results in a Foo being created and later destroyed when SomeFunc function returns.
If you change the function signature to:
SomeFunc(Foo& obj);
or better:
SomeFunc(const Foo& obj);
problem goes away.
What is puzzling however is why the code crashes on the obj.PrintVal(); line.
I can understand how on calling SomeFunc that a new Foo is created and destroyed when the function returns, but I thought that would be isolated to the local copy of obj in SomeFunc. But when I step through in my debugger I find that the ptr of obj in main is deallocated. and so on calling obj.PrintVal() - the dereference of ptr causes segmentation fault / access violation.
Can someone please explain what is happening.
#include <iostream>
class Foo
{
public:
int *ptr;
Foo(int i) {
ptr = new int(i);
}
~Foo() {
delete ptr;
}
int PrintVal() {
std::cout << *ptr;
return *ptr;
}
};
void SomeFunc(Foo obj) {
int x = obj.PrintVal();
}
int main() {
{
Foo obj= 15;
SomeFunc(obj);
obj.PrintVal();
}
return 0;
}
It's "crashing" because you have made a copy of that pointer unintentionally, and the delete is called on an already deleted pointer.
You need to provide a copy constructor (different from the automatically created one), that does handle this correctly (create a new pointer for the copy).

is it possible to do class_inst = some_func(class_inst) just the way we do it for built-in datatypes? [duplicate]

This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 8 years ago.
i have a little program that tries to do it but fails
class myclass{
public:
int * ptr;
myclass (){
ptr = new int;
}
myclass (const myclass &class_inst){
ptr = new int;
*ptr = *class_inst.ptr;
}
~myclass (){
delete ptr;
}
};
myclass dosomething (myclass a){
// make some changes to a
return a;
}
int main(){
myclass test1;
test1 = dosomething (test1);
return 0;
}
after test1 = dosomething.. is executed, test1's destructor is called. it gets called again at the end of main and that causes a seg fault.
1 way to fix this would be to have dosomething as a member function and use test1.dosomething(). Id like to know what is wrong with the above code.
Thanks!
You allocate memory for the single int, store the pointer to it to ptr, and then overwrite the same pointer with class_inst's pointer. When destructed both objects try to deallocate the same memory block.
I assume you wanted to copy the contents.
myclass (const myclass &class_inst){
ptr = new int;
*ptr = *class_inst.ptr;
}
Echoing Mooing Duck's comment about the rule of three, I will try and walk through what happens at each step of your main (apologies for any mangled indentation):
int main(){
myclass test1; //myclass default ctor called.
//ptr assigned a new int (uninitialised)
test1 = dosomething (test1); //make a copy of test1
//a.ptr is assigned a new int and then assigned class_inst.ptr, losing the original “new int” which will be leaked
//return a copy (call it result) constructed my class of argument a (which is a copy of test 1)
//result.ptr is assigned a new int and then assigned class_inst.ptr,
//losing the original “new int” which will be leaked
//a goes out of scope, and calls its door which deletes it’s a.ptr, which is pointed to by result.ptr (which in turn is class_inst.ptr)
return 0; //test1 (which is the same as result above) goes out of scope and tries to delete its ptr member, which is != NULL
//and then you get the seg fault
}
So what you should do is look up the rule of three (aka the big three), think about what happens in the default and copy constructors really hard, and equally so about the destructor.

What's the difference between new MyClass and new MyClass() [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between A* pA = new A; and A* pA = new A();
Variable initialization (pointer and value)
Assuming that MyClass has a default constructor, what's the difference between
MyClass *mc = new MyClass;
and
MyClass *mc = new MyClass();
Assuming that MyClass has a default constructor
2 extra characters in the code.
If the class is a POD type (not your case), the latter will perform value-initialization.