0

first of all i hope this isnt a dublicate. Im am a java programmer and changing to c++ now. In java you can do like this

 Object obj = new Object();

and to my understanding you can the same thing in c++ (seeing how obj in java will only be saved in the variable as a reference) like this:

Object* obj = new Object();

My question is this: How long does this object live? does it live as long as the pointer does ? also, is this possible to do will member initilazion of an object ? And if so will the object live as long as the pointer is saved as a member vairable (until that object you store it in is destroyes)?

Srry for any typos. Have a nice day/nigth!

5 Answers5

6

The object lives until someone calls delete on the pointer that points to it. You should not use new and delete unless you are implementing some library functionality where there is no other option, and you really know what you are doing. The default action should be not to use new directly, unless it is to initialize a smart pointer or to insert into some class that takes care of memory management for you.

This would be the C++ way of creating a default constructed instance of Object:

Object obj; // calls the default constructor
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • ok:( i will keep that in mind. Trying to find a way to initialize a vector as a member variable. Maby i should make a new question about that :P – Fredrik Boston Westman Feb 25 '13 at 21:35
  • 2
    @FredrikBostonWestman you don't have to do anything special. The default constructor of the vector does something sensible. – juanchopanza Feb 25 '13 at 21:36
  • 3
    AFAIK the most common garbage collector for C++ is the **[Boehm collector](http://www.hpl.hp.com/personal/Hans_Boehm/gc/)**. It's been used since at least C++03. The C++11 standard added some minimal support for garbage collection, namely **`std::declare_reachable`**, **`std::undeclare_reachable`**, **`std::declare_no_pointers`**, **`std::undeclare_no_pointers`** and **`std::get_pointer_safety`**. – Cheers and hth. - Alf Feb 25 '13 at 21:42
2

How long does this object live?

Until you explicitially delete it. Unlike in Java, objects in C++ that are dynamically instantiated via new have user-controlled lifetimes and are not garbage collected, so they are not automatically freed when all references to them disappear. If you want that behavior, there are classes like std::auto_ptr and std::unique_ptr to handle that for you.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

You create an object like this.

In the .h file, you have the follow Object *foo;

In the .cpp class, you initialise the class similar to java.

foo = new Object();

You then delete it using the delete keyword - so delete foo in this case.

I'm in a similar boat to you. I highly recommend getting your head around pointers (the * thing) - it's really powerful.

Edit: as said above, you can also just do Object foo to create the object on the stack, rather than the heap.

Chris O'Brien
  • 372
  • 6
  • 25
  • yh :P im in the swamp of * and &. I Know the diffrence between them, but when i come to initializing objects, passing them in to function ect. So confusing when to use what :P – Fredrik Boston Westman Feb 25 '13 at 21:39
  • I'm not quite there with & yet. Baby steps are best. I used to writer 30-50 lines of code with java, press compile and hope for the best! I find myself planning and saving and compiling with every key press! – Chris O'Brien Feb 25 '13 at 21:44
  • i recomend you watch thenewBoston c++ tutorials on youtube :) a bit slow but he explains alot of stuff. Tho its kinda basic stuff – Fredrik Boston Westman Feb 25 '13 at 21:46
0

In C or C++, it will live until it's deleted. You typically want to wrap any resource allocation/deallocation (which can include calls to new/delete and malloc/free) in a ctor dtor pair. e.g.

class ObjectManager
{
public:
    ObjectManager()
        : mObjectPtr(0)
    {
        mObjectPtr = new Object();
    }

    ~ObjectManager()
    {
        delete mObject;
    }
private:
    Object* mObjectPtr;
};

If you use that, you should add some error handling in case something goes wrong in new.

john.pavan
  • 910
  • 4
  • 6
  • 1
    Not in C, since C does not have `new` and `delete`. – Jonathan Grynspan Feb 25 '13 at 21:34
  • This is this RAII everybody is talking about rigth ? and while this is good, im unsure how this will solve my put it as a member variable issue i have :O – Fredrik Boston Westman Feb 25 '13 at 21:43
  • 1
    A destructor is not enough. If you're going to go this route, you also need either define or disable (at least) the copy constructor and the assignment operator. And for C++11 you should also define a move constructor and a move assignment operator. – Benjamin Lindley Feb 25 '13 at 21:50
0

There is no guaranteed garbage collector in C++ so it will live until it is explicitly deleted.

If you want to use pointers and like something a bit more managed you can use a smart pointer

std::unique_ptr<Object> Obj = new Object();

There are a few different types of smart pointers, as per the linked answer, but basically a smart pointer will automatically destroy the object once it goes out of scope.

As for member initialisation part of your question you can do

TestMe()
{
  Object Obj();

  //Do something with object

}

Then Obj gets created on the stack and is destroyed automatically when it goes out of scope.

Community
  • 1
  • 1
James
  • 88
  • 6
  • -1 "There is no garbage collector in C++ so..." is incorrect. there is no guaranteed garbage collection, though: you have to explicitly use a garbage collector, and the language's support for that is pretty limited. it would have helped to read the other answers and comments before posting your own. – Cheers and hth. - Alf Feb 25 '13 at 22:07