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

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.

Related

If a function uses 'new' and returns the variable, and if we don't assign it in our main, can we delete it? [duplicate]

I learned C# first, and now I'm starting with C++. As I understand, operator new in C++ is not similar to the one in C#.
Can you explain the reason of the memory leak in this sample code?
class A { ... };
struct B { ... };
A *object1 = new A();
B object2 = *(new B());
What is happening
When you write T t; you're creating an object of type T with automatic storage duration. It will get cleaned up automatically when it goes out of scope.
When you write new T() you're creating an object of type T with dynamic storage duration. It won't get cleaned up automatically.
You need to pass a pointer to it to delete in order to clean it up:
However, your second example is worse: you're dereferencing the pointer, and making a copy of the object. This way you lose the pointer to the object created with new, so you can never delete it even if you wanted!
What you should do
You should prefer automatic storage duration. Need a new object, just write:
A a; // a new object of type A
B b; // a new object of type B
If you do need dynamic storage duration, store the pointer to the allocated object in an automatic storage duration object that deletes it automatically.
template <typename T>
class automatic_pointer {
public:
automatic_pointer(T* pointer) : pointer(pointer) {}
// destructor: gets called upon cleanup
// in this case, we want to use delete
~automatic_pointer() { delete pointer; }
// emulate pointers!
// with this we can write *p
T& operator*() const { return *pointer; }
// and with this we can write p->f()
T* operator->() const { return pointer; }
private:
T* pointer;
// for this example, I'll just forbid copies
// a smarter class could deal with this some other way
automatic_pointer(automatic_pointer const&);
automatic_pointer& operator=(automatic_pointer const&);
};
automatic_pointer<A> a(new A()); // acts like a pointer, but deletes automatically
automatic_pointer<B> b(new B()); // acts like a pointer, but deletes automatically
This is a common idiom that goes by the not-very-descriptive name RAII (Resource Acquisition Is Initialization). When you acquire a resource that needs cleanup, you stick it in an object of automatic storage duration so you don't need to worry about cleaning it up. This applies to any resource, be it memory, open files, network connections, or whatever you fancy.
This automatic_pointer thing already exists in various forms, I've just provided it to give an example. A very similar class exists in the standard library called std::unique_ptr.
There's also an old one (pre-C++11) named auto_ptr but it's now deprecated because it has a strange copying behaviour.
And then there are some even smarter examples, like std::shared_ptr, that allows multiple pointers to the same object and only cleans it up when the last pointer is destroyed.
A step by step explanation:
// creates a new object on the heap:
new B()
// dereferences the object
*(new B())
// calls the copy constructor of B on the object
B object2 = *(new B());
So by the end of this, you have an object on the heap with no pointer to it, so it's impossible to delete.
The other sample:
A *object1 = new A();
is a memory leak only if you forget to delete the allocated memory:
delete object1;
In C++ there are objects with automatic storage, those created on the stack, which are automatically disposed of, and objects with dynamic storage, on the heap, which you allocate with new and are required to free yourself with delete. (this is all roughly put)
Think that you should have a delete for every object allocated with new.
EDIT
Come to think of it, object2 doesn't have to be a memory leak.
The following code is just to make a point, it's a bad idea, don't ever like code like this:
class B
{
public:
B() {}; //default constructor
B(const B& other) //copy constructor, this will be called
//on the line B object2 = *(new B())
{
delete &other;
}
}
In this case, since other is passed by reference, it will be the exact object pointed to by new B(). Therefore, getting its address by &other and deleting the pointer would free the memory.
But I can't stress this enough, don't do this. It's just here to make a point.
Given two "objects":
obj a;
obj b;
They won't occupy the same location in memory. In other words, &a != &b
Assigning the value of one to the other won't change their location, but it will change their contents:
obj a;
obj b = a;
//a == b, but &a != &b
Intuitively, pointer "objects" work the same way:
obj *a;
obj *b = a;
//a == b, but &a != &b
Now, let's look at your example:
A *object1 = new A();
This is assigning the value of new A() to object1. The value is a pointer, meaning object1 == new A(), but &object1 != &(new A()). (Note that this example is not valid code, it is only for explanation)
Because the value of the pointer is preserved, we can free the memory it points to: delete object1; Due to our rule, this behaves the same as delete (new A()); which has no leak.
For you second example, you are copying the pointed-to object. The value is the contents of that object, not the actual pointer. As in every other case, &object2 != &*(new A()).
B object2 = *(new B());
We have lost the pointer to the allocated memory, and thus we cannot free it. delete &object2; may seem like it would work, but because &object2 != &*(new A()), it is not equivalent to delete (new A()) and so invalid.
In C# and Java, you use new to create an instance of any class and then you do not need to worry about destroying it later.
C++ also has a keyword "new" which creates an object but unlike in Java or C#, it is not the only way to create an object.
C++ has two mechanisms to create an object:
automatic
dynamic
With automatic creation you create the object in a scoped environment:
- in a function or
- as a member of a class (or struct).
In a function you would create it this way:
int func()
{
A a;
B b( 1, 2 );
}
Within a class you would normally create it this way:
class A
{
B b;
public:
A();
};
A::A() :
b( 1, 2 )
{
}
In the first case, the objects are destroyed automatically when the scope block is exited. This could be a function or a scope-block within a function.
In the latter case the object b is destroyed together with the instance of A in which it is a member.
Objects are allocated with new when you need to control the lifetime of the object and then it requires delete to destroy it. With the technique known as RAII, you take care of the deletion of the object at the point you create it by putting it within an automatic object, and wait for that automatic object's destructor to take effect.
One such object is a shared_ptr which will invoke a "deleter" logic but only when all the instances of the shared_ptr that are sharing the object are destroyed.
In general, whilst your code may have many calls to new, you should have limited calls to delete and should always make sure these are called from destructors or "deleter" objects that are put into smart-pointers.
Your destructors should also never throw exceptions.
If you do this, you will have few memory leaks.
B object2 = *(new B());
This line is the cause of the leak. Let's pick this apart a bit..
object2 is a variable of type B, stored at say address 1 (Yes, I'm picking arbitrary numbers here). On the right side, you've asked for a new B, or a pointer to an object of type B. The program gladly gives this to you and assigns your new B to address 2 and also creates a pointer in address 3. Now, the only way to access the data in address 2 is via the pointer in address 3. Next, you dereferenced the pointer using * to get the data that the pointer is pointing to (the data in address 2). This effectively creates a copy of that data and assigns it to object2, assigned in address 1. Remember, it's a COPY, not the original.
Now, here's the problem:
You never actually stored that pointer anywhere you can use it! Once this assignment is finished, the pointer (memory in address3, which you used to access address2) is out of scope and beyond your reach! You can no longer call delete on it and therefore cannot clean up the memory in address2. What you are left with is a copy of the data from address2 in address1. Two of the same things sitting in memory. One you can access, the other you can't (because you lost the path to it). That's why this is a memory leak.
I would suggest coming from your C# background that you read up a lot on how pointers in C++ work. They are an advanced topic and can take some time to grasp, but their use will be invaluable to you.
Well, you create a memory leak if you don't at some point free the memory you've allocated using the new operator by passing a pointer to that memory to the delete operator.
In your two cases above:
A *object1 = new A();
Here you aren't using delete to free the memory, so if and when your object1 pointer goes out of scope, you'll have a memory leak, because you'll have lost the pointer and so can't use the delete operator on it.
And here
B object2 = *(new B());
you are discarding the pointer returned by new B(), and so can never pass that pointer to delete for the memory to be freed. Hence another memory leak.
If it makes it easier, think of computer memory as being like a hotel and programs are customers who hire rooms when they need them.
The way this hotel works is that you book a room and tell the porter when you are leaving.
If you program books a room and leaves without telling the porter the porter will think that the room is still is use and will not let anyone else use it. In this case there is a room leak.
If your program allocates memory and does not delete it (it merely stops using it) then the computer thinks that the memory is still in use and will not allow anyone else to use it. This is a memory leak.
This is not an exact analogy but it might help.
When creating object2 you're creating a copy of the object you created with new, but you're also losing the (never assigned) pointer (so there's no way to delete it later on). To avoid this, you'd have to make object2 a reference.
It's this line that is immediately leaking:
B object2 = *(new B());
Here you are creating a new B object on the heap, then creating a copy on the stack. The one that has been allocated on the heap can no longer be accessed and hence the leak.
This line is not immediately leaky:
A *object1 = new A();
There would be a leak if you never deleted object1 though.

Who deletes pointer (not created with new) in C++?

I'm trying to understand the concept behind pointers.
I have a function in which i set an pointer to an object as an attribute of a struct:
void util::setobject(string s)
{
Document* d;
d->Parse(s.c_str());
message.payload = d;
{
Outside this function i can call the message object and access the document. Now I call this function for the second time so I overwrite the payload and set a new pointer to a new document. As far as I know, the old document object still exists but nothing points to it correct? Is this object then removed automatically?
Thanks!
Edit
Sorry I totally messed up this code example.
So I have two options here:
Option 1: Stay with pointers
void util::setobject(string s)
{
Document* d = new Document();
d->Parse(s.c_str());
message.payload = d;
{
To avoid a memory leak i would need to delete the pointed object before assigning new value, correct?
void util::setobject(string s)
{
Document* d = new Document();
d->Parse(s.c_str());
delete message.payload; // correct?
message.payload = d;
{
Second option: Avoid using "new"
void util::setobject(string s)
{
Document d;
d.Parse(s.c_str());
message.payload = d; // object is copied to struct attribute
{
S.th. like that wouldn't work because d goes out of scope:
void util::setobject(string s)
{
Document d;
d.Parse(s.c_str());
message.payload = &d; // does not make sense correct?
{
This might be s.th. off-topic, but the second version would require the struct to look like that:
struct MESSSAGE
{
string topic;
bool done = true;
Document payload;
}
Document comes from <rapidjson/document.h>. Doing it without a pointer results in multiple errors:
error: use of deleted function 'Message::Message(const Message&)'
'rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>::GenericDocument(const rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>&) [with Encoding=rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>; StackAllocator=rapidjson::CrtAllocator]' is private within this context
Does anyone also know how to interpret these errors? I think that the copy constructor of Document is private, therefore I need to use pointer here, correct?
Who deletes pointer (not created with new) in C++?
As long as the program is well defined, no one deletes pointer-not-created-with-new because only pointer-created-with-allocating-new may be deleted.
Document* d;
d->Parse(s.c_str());
The behaviour of this example is undefined because you indirect through an uninitialised pointer and attempt to call a member function through it.
message.payload = d;
Here, you copy an indeterminate value. Behaviour is undefined because of this as well.
... an can be used like this
You are mistaken. No pointer can be used like this.
so I overwrite the payload and set a new pointer to a new document.
In the example, you don't set pointer to a "new document". You never created a document in the example.
As far as I know, the old document object still exists
If message.payload used to point to a document object, then that object still exists. You haven't demonstrated such case in the example.
but nothing points to it correct?
Depends. There can be many pointers to an object, so overwriting one pointer doesn't necessarily mean that there are no pointers to the object any more. But indeed, this is a possible case - that wasn't demonstrated in the example.
Is this object then removed automatically?
Depends on the storage class of the object. automatic objects are destroyed automatically (hint is in the name) when they go out of scope. Static objects are destroyed automatically when the program ends. Thread local objects are destroyed automatically when the thread exits. Temporary objects are destroyed automatically at the end of full expression (sometimes extended).
Dynamic objects are not destroyed automatically. They are destroyed only when explicitly destroyed or deleted. If last pointer to dynamic object is overwritten, that object is said to have been leaked. Well, dynamic trivial objects can be destroyed automatically by creating another object in its place, but dynamic memory is not deallocated automatically.
Regarding the edited question;
To avoid a memory leak i would need to delete the pointed object before assigning new value, correct?
Depends on what the old pointer points to. If it points to a dynamic object created with allocating new and there are no other pointers responsible for the deletion, then yes. Otherwise, no.
Does anyone also know how to interpret these errors?
Document is not (publicly) copyable, and you attempted to copy Message which contains such non-copyable document.
There is no Document in your code, hence there is nothing you could delete.
What this function does
void util::setobject(string s)
{
Document* d;
d->Parse(s.c_str());
message.payload = d;
}
is the following:
It declares d as a pointer to a Document and leaves that pointer uninitialized. The second line then dereferences that uninitialized pointer and causes undefined behavior.
I suggest you to read Why should C++ programmers minimize use of 'new'?, because your function should actually look like this:
void util::setobject(string s)
{
Document d;
d.Parse(s.c_str());
message.payload = d;
}
If you cannot / do not want to change payload to be a Document (not a pointer), then you need to create a Document:
Document* d = new Document;
However, you should not use raw pointers here. Look at std::shared_ptr or std::unique_ptr. Raw pointers should not be owning memory. To "own" something means to be responsible to delete it. Smart pointers do that for you, while raw owning pointers are a recipe for desaster and should be avoided (don't misunderstand: raw pointers are fine, the problem is owning raw pointers).
To answer the title question: No-one.
Only pointers that point to objects allocated by new should be deleted and only pointers that point to objects allocated by new[] should be delete[]d.
Pointers to objects that have static1, thread local2 or automatic3 storage duration must not be deleted, the language specifies how and when those objects are destroyed.
"Global" objects
"Per-thread global" objects
"On-the-Stack" objects

C++ Difference between *new and new [duplicate]

This question already has answers here:
Why does the use of 'new' cause memory leaks?
(9 answers)
Closed 9 years ago.
This question may be a duplicate. I have been looking online everywhere to figure this out, but I can't find anything. What is the difference between 'new' and '*new'?:
int main()
{
class Cat
{
//Code
}
new Cat();
*new Cat();
return 0;
}
These are not two separate things. There's not a new and a *new. The second is simply applying unary * to the result of new Cat().
new Cat() is a new-expression. It dynamically allocates and initialises a Cat object and evaluates to a pointer to that object. If you then apply unary * to that pointer, you dereference it to get the Cat object.
There is not very often a good reason to apply unary * immediately to a new-expression. The reason is because you're immediately following the pointer and haven't stored the pointer anywhere. Consider if you had done this:
Cat c = *new Cat();
This would result in a memory leak that you can't recover from. A Cat object is dynamically allocated and then copied into c. The dynamically allocated Cat now lingers around and you don't have a pointer to it through which you can delete the object. This is very bad.
Cat& c = *new Cat();
This is a little better, because at least now c is just a reference to the dynamically allocated object. You can always do delete &c; to destroy the object. However, it masks the fact that Cat was dynamically allocated. If I were reading this code, I wouldn't expect c to be referring to a dynamically allocated object.
You must remember to destroy dynamically allocated objects. Dereferencing the result of a new-expression makes that more difficult to achieve, so avoid it.
This expression:
new Cat();
Creates dynamically an object of type Cat, and you are ignoring the returned pointer (not storing it, not dereferencing, nothing). This expression:
*new Cat();
Does the same as the one above, except that you are also dereferencing the pointer returned by new. But dereferencing a pointer per se is an operation has no side-effect.
Concretely, therefore, the effect of both expressions is the same. The important bit is that you are leaking memory twice by losing the one and only reference to the objects you create dynamically.
Keep in mind that every object created with new must be destroyed by a corresponding call to delete. For instance, if you stored the returned pointer this way:
Cat* pCat = new Cat();
That would allow you to do, later on:
delete pCat;
And avoid memory leaks. Also, this:
Cat& cat = *new Cat();
Would allow you to do, later on:
delete &cat;
And avoid memory leaks again. Notice, however, that this would not be an option:
Cat cat = *new Cat();
The above would still give you a memory leak. The reason is that it would copy the object obtained by dereferencing the pointer returned by new into cat. In other words, cat would be a different object than (although identical to) the one the new expression created.
The object created by the new expression, on the other hand, would be lost - resulting in a memory leak again.
In Modern C++, it is advisable to avoid manual memory management by calling new and delete; rather, consider using smart pointers (which one depends on the ownership policy that you need). For instance:
#include <memory>
// ...
std::shared_ptr<Cat> pCat = std::make_shared<Cat>();
Smart pointers take care of automatically destroying the referenced object when the last smart pointer to the pointed object is destroyed.
Does it help you:
Cat *ptr = new Cat();
Cat cat = *new Cat(); /* memory leak :( */

C++ what does & do in overloaded assignment operator declaration? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does the use of ‘new’ cause memory leaks?
What is the difference between (if there is one):
Player player=*(new Player());
and:
Player &player=*(new Player());
Both (seem to) behave the same way, but I surely miss something?!?
The difference is that the first makes a copy, whereas the second creates a reference to the object pointed to by the pointer returned by new Player().
Player player=*(new Player());
copy-initializes player using the copy-constructor.
Player &player=*(new Player());
just creates an alias for *(new Player()), which is valid because new Player() isn't a temporary. Player& player = Player() would be illegal because of that.
They're the same in that they both suck.
new Player() is an expression that creates an object (unnamed) on the so-called heap. The result of the expression is a pointer to the newly created object. Now when you do
Player player = *(new Player())
you define a variable named player that is a copy of the newly created object. Moreover, you've lost all handles (access) to the heap object, and you can never free the memory it occupies.
On the other hand,
Player &player=*(new Player());
creates a reference named player to the newly created object. Thus, you have access to that object. In particular, you can free the memory and destroy that object by
delete &player;

Why does the use of 'new' cause memory leaks?

I learned C# first, and now I'm starting with C++. As I understand, operator new in C++ is not similar to the one in C#.
Can you explain the reason of the memory leak in this sample code?
class A { ... };
struct B { ... };
A *object1 = new A();
B object2 = *(new B());
What is happening
When you write T t; you're creating an object of type T with automatic storage duration. It will get cleaned up automatically when it goes out of scope.
When you write new T() you're creating an object of type T with dynamic storage duration. It won't get cleaned up automatically.
You need to pass a pointer to it to delete in order to clean it up:
However, your second example is worse: you're dereferencing the pointer, and making a copy of the object. This way you lose the pointer to the object created with new, so you can never delete it even if you wanted!
What you should do
You should prefer automatic storage duration. Need a new object, just write:
A a; // a new object of type A
B b; // a new object of type B
If you do need dynamic storage duration, store the pointer to the allocated object in an automatic storage duration object that deletes it automatically.
template <typename T>
class automatic_pointer {
public:
automatic_pointer(T* pointer) : pointer(pointer) {}
// destructor: gets called upon cleanup
// in this case, we want to use delete
~automatic_pointer() { delete pointer; }
// emulate pointers!
// with this we can write *p
T& operator*() const { return *pointer; }
// and with this we can write p->f()
T* operator->() const { return pointer; }
private:
T* pointer;
// for this example, I'll just forbid copies
// a smarter class could deal with this some other way
automatic_pointer(automatic_pointer const&);
automatic_pointer& operator=(automatic_pointer const&);
};
automatic_pointer<A> a(new A()); // acts like a pointer, but deletes automatically
automatic_pointer<B> b(new B()); // acts like a pointer, but deletes automatically
This is a common idiom that goes by the not-very-descriptive name RAII (Resource Acquisition Is Initialization). When you acquire a resource that needs cleanup, you stick it in an object of automatic storage duration so you don't need to worry about cleaning it up. This applies to any resource, be it memory, open files, network connections, or whatever you fancy.
This automatic_pointer thing already exists in various forms, I've just provided it to give an example. A very similar class exists in the standard library called std::unique_ptr.
There's also an old one (pre-C++11) named auto_ptr but it's now deprecated because it has a strange copying behaviour.
And then there are some even smarter examples, like std::shared_ptr, that allows multiple pointers to the same object and only cleans it up when the last pointer is destroyed.
A step by step explanation:
// creates a new object on the heap:
new B()
// dereferences the object
*(new B())
// calls the copy constructor of B on the object
B object2 = *(new B());
So by the end of this, you have an object on the heap with no pointer to it, so it's impossible to delete.
The other sample:
A *object1 = new A();
is a memory leak only if you forget to delete the allocated memory:
delete object1;
In C++ there are objects with automatic storage, those created on the stack, which are automatically disposed of, and objects with dynamic storage, on the heap, which you allocate with new and are required to free yourself with delete. (this is all roughly put)
Think that you should have a delete for every object allocated with new.
EDIT
Come to think of it, object2 doesn't have to be a memory leak.
The following code is just to make a point, it's a bad idea, don't ever like code like this:
class B
{
public:
B() {}; //default constructor
B(const B& other) //copy constructor, this will be called
//on the line B object2 = *(new B())
{
delete &other;
}
}
In this case, since other is passed by reference, it will be the exact object pointed to by new B(). Therefore, getting its address by &other and deleting the pointer would free the memory.
But I can't stress this enough, don't do this. It's just here to make a point.
Given two "objects":
obj a;
obj b;
They won't occupy the same location in memory. In other words, &a != &b
Assigning the value of one to the other won't change their location, but it will change their contents:
obj a;
obj b = a;
//a == b, but &a != &b
Intuitively, pointer "objects" work the same way:
obj *a;
obj *b = a;
//a == b, but &a != &b
Now, let's look at your example:
A *object1 = new A();
This is assigning the value of new A() to object1. The value is a pointer, meaning object1 == new A(), but &object1 != &(new A()). (Note that this example is not valid code, it is only for explanation)
Because the value of the pointer is preserved, we can free the memory it points to: delete object1; Due to our rule, this behaves the same as delete (new A()); which has no leak.
For you second example, you are copying the pointed-to object. The value is the contents of that object, not the actual pointer. As in every other case, &object2 != &*(new A()).
B object2 = *(new B());
We have lost the pointer to the allocated memory, and thus we cannot free it. delete &object2; may seem like it would work, but because &object2 != &*(new A()), it is not equivalent to delete (new A()) and so invalid.
In C# and Java, you use new to create an instance of any class and then you do not need to worry about destroying it later.
C++ also has a keyword "new" which creates an object but unlike in Java or C#, it is not the only way to create an object.
C++ has two mechanisms to create an object:
automatic
dynamic
With automatic creation you create the object in a scoped environment:
- in a function or
- as a member of a class (or struct).
In a function you would create it this way:
int func()
{
A a;
B b( 1, 2 );
}
Within a class you would normally create it this way:
class A
{
B b;
public:
A();
};
A::A() :
b( 1, 2 )
{
}
In the first case, the objects are destroyed automatically when the scope block is exited. This could be a function or a scope-block within a function.
In the latter case the object b is destroyed together with the instance of A in which it is a member.
Objects are allocated with new when you need to control the lifetime of the object and then it requires delete to destroy it. With the technique known as RAII, you take care of the deletion of the object at the point you create it by putting it within an automatic object, and wait for that automatic object's destructor to take effect.
One such object is a shared_ptr which will invoke a "deleter" logic but only when all the instances of the shared_ptr that are sharing the object are destroyed.
In general, whilst your code may have many calls to new, you should have limited calls to delete and should always make sure these are called from destructors or "deleter" objects that are put into smart-pointers.
Your destructors should also never throw exceptions.
If you do this, you will have few memory leaks.
B object2 = *(new B());
This line is the cause of the leak. Let's pick this apart a bit..
object2 is a variable of type B, stored at say address 1 (Yes, I'm picking arbitrary numbers here). On the right side, you've asked for a new B, or a pointer to an object of type B. The program gladly gives this to you and assigns your new B to address 2 and also creates a pointer in address 3. Now, the only way to access the data in address 2 is via the pointer in address 3. Next, you dereferenced the pointer using * to get the data that the pointer is pointing to (the data in address 2). This effectively creates a copy of that data and assigns it to object2, assigned in address 1. Remember, it's a COPY, not the original.
Now, here's the problem:
You never actually stored that pointer anywhere you can use it! Once this assignment is finished, the pointer (memory in address3, which you used to access address2) is out of scope and beyond your reach! You can no longer call delete on it and therefore cannot clean up the memory in address2. What you are left with is a copy of the data from address2 in address1. Two of the same things sitting in memory. One you can access, the other you can't (because you lost the path to it). That's why this is a memory leak.
I would suggest coming from your C# background that you read up a lot on how pointers in C++ work. They are an advanced topic and can take some time to grasp, but their use will be invaluable to you.
Well, you create a memory leak if you don't at some point free the memory you've allocated using the new operator by passing a pointer to that memory to the delete operator.
In your two cases above:
A *object1 = new A();
Here you aren't using delete to free the memory, so if and when your object1 pointer goes out of scope, you'll have a memory leak, because you'll have lost the pointer and so can't use the delete operator on it.
And here
B object2 = *(new B());
you are discarding the pointer returned by new B(), and so can never pass that pointer to delete for the memory to be freed. Hence another memory leak.
If it makes it easier, think of computer memory as being like a hotel and programs are customers who hire rooms when they need them.
The way this hotel works is that you book a room and tell the porter when you are leaving.
If you program books a room and leaves without telling the porter the porter will think that the room is still is use and will not let anyone else use it. In this case there is a room leak.
If your program allocates memory and does not delete it (it merely stops using it) then the computer thinks that the memory is still in use and will not allow anyone else to use it. This is a memory leak.
This is not an exact analogy but it might help.
When creating object2 you're creating a copy of the object you created with new, but you're also losing the (never assigned) pointer (so there's no way to delete it later on). To avoid this, you'd have to make object2 a reference.
It's this line that is immediately leaking:
B object2 = *(new B());
Here you are creating a new B object on the heap, then creating a copy on the stack. The one that has been allocated on the heap can no longer be accessed and hence the leak.
This line is not immediately leaky:
A *object1 = new A();
There would be a leak if you never deleted object1 though.