c++ - beginner and cpp class -


i'm using code under "constructors , destructors" here

basically, combine pointer construction under "pointers classes" (a little below) find neat.

now works:

int main () {    crectangle * prect;     //l2    crectangle rect (3,4);  //l3    prect = &rect;          //l4    cout << "rect area: " << (*prect).area() << endl;    return 0; } 

my questions is, can replace l2-l4 more elegant method not requiring creation of rect on line 3?

to create object without requiring automatic variables (such rect in code above) must use new operator. objects created new operator stored in free store, , new expression evaluates pointer newly created object.

now, 1 go on , say, new operator answer , that's it, it's not: not answer question of replacing couple of lines more elegant solution, because wouldn't one.

the rest of answer goes on tangent of how new used.

unlike automatic objects, objects stored in free store not automatically destructed, rather life-time , destruction controlled delete operator (you should delete objects no longer need free resources). ensure destruction, should store pointer new expression what's called smart pointer. good, simple rule carries 1 far: use new operator inside smart pointer constructor (unless know you're doing).

there several smart pointers in c++11, while earlier versions of standard defined one, auto_ptr. perhaps due it's quirks, or because got replacement, it's deprecated in c++11, , shouldn't used in new code, @ least not in c++11 (now, opinion).

an example of smart pointer use:

boost::shared_ptr<crectangle> shared_rect(new crectange(3, 4)); std::unique_ptr<crectangle> rect(new crectangle(3, 4)); // c++11  // use smart pointers like regular pointers; indirection through * or -> // i.e. (*rect).area() or rect->area() 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -