I have a class called polynomial. Its a nothing little class right now,
with just int variables, a basic container class. Im using it as I go
through some tutorials, but in this particular tutorial its telling me to do
polynomial *first = new polynomial();
but before I found this site I was just doing
polynomial first;
Im also struggling through pointers. I understand the basics, but fail to
see the advantage using them with my objects so quickly. Is one way better
than the other?
Thanks
> Im also struggling through pointers. I understand the basics, but fail to
> see the advantage using them with my objects so quickly. Is one way
> better than the other?
In C++, most types should be value types, behaving and used like 'int'.
Instances only should be allocated with new when they can't or shouldn't
be copied, when an object instance needs to be shared/accessed from
multiple locations, or when the lifetime of the object needs to be
explicitly controlled.
Don't use 'new' until you find out that you have to.
I hope this helps,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
It's likely that you are right and the tutorial is wrong. If it works
without new then don't use it. Avoiding new leads to clearer code (because
the lifetime of the object is limited) and more efficient code (for the same
reason). Occaisionally you see code like this
{
Wotsit* w = new Wotsit();
...
delete w;
}
That's clearly rubbish because the object lifetime is exactly the same as if
w was an automatic variable.
{
Wotsit w;
...
}
The second version is exception safe too.
> Im also struggling through pointers. I understand the basics, but fail to
> see the advantage using them with my objects so quickly. Is one way
> better than the other?
Same advice again, if you don't see the need for pointers don't use them.
They are tricky to use correctly so avoid them if you can. But I find it
surprising that you don't see the need if you have been programming Java, in
Java almost everything is a pointer.
john
But in C++, if you write
Polynomial* createNew() {
Polynomial pn;
return &pn;
}
It doesn't work. It may be compiled and linked but actually it's very
dangerous. The instance of Polynomial is constructed when the function is
called, but also is destroyed as soon as the function returns. However, the
caller gets the pointer of that nonexistent object returned by the function
and takes it as a valid pointer.
We want a way to create new objects other than in the stack, so that we can
hold the objects even if the functions that create them return. So we get
heap. We use "new expression" to create new objects in the heap - another
special memory area where objects created by "new expressions" exist. Thus
we can write the following codes in C++:
Polynomial* createNew() {
Polynomial* ppn = new Polynomial;
return ppn;
}
Memory allocated by "new expressions" can and only can be freed by "delete"
in the C++ codes. So here comes another thing: delete anything you created
by new (after they are useless, but before you lose the pointers of them).
Unlike in Java, the system doesn't clear the useless objects created by new
here.
"Rv5" <rmo...@adelphia.net> 写入消息新闻:6aSdnVDuQIn...@adelphia.com...
That said, and back to a spin off of my original question, if I do need just
a pointer to an object and not an object itself, would i use "new" in that
case? For example:
myobject *pointer = new myobject
Just trying to figure out possible scenarios.
ross
No, again, unless you need the lifetime of the object to extend
the current function scope.
What you would write instead is:
myobject obj;
myobject* pointer = &obj;
But I do not see in what scenario you would want to do that.
When the ownership( = responsibility to destroy) of the object
is passed to another function, it is usually better to use
a smart pointer, such as std::auto_ptr.
Also, in many uses of pointers, in C++ it is better to use
references instead (e.g. as function parameters...).
hth
Why does one want to do this:
Polynomial* p1 = OtherPoly.createNew();
instead of:
Polynomial p1 = OtherPoly;
??
I've never programmed much Java so I don't get the idea here. I think
you don't have to new/delete at all if you're from java world. If you
use container classes you have all the java functionality without
caring about new/delete. Correct me if I'm wrong.
-Gernot
Declaring pointers all over the place is no way to write C++. Only use a
pointer when you need to control the lifetime of an object.
No, this is the common mistake. New is about the *lifetime* of the object
being created. An object created with new lives until you call delete,
that's what makes objects create with new different from automatic objects,
not pointers.
You can get a pointer to any object. If you want a pointer to an automatic
object use the & operator.
john
I didn't mean that createNew() is a method of class Polynomial. However, no
matter whether it is or not. It's not my point. I was just saying that, you
can easily create a new object in a function in Java and return its
handle(or reference, or pointer) to the caller so that the caller can
control that object(by calling its method). But in C++, you can't do this
easily because the object you create within a function as a local variable
is destroyed automatically after the function returns. Thus the pointer it
returns doesn't point to a valid object any longer. So you have to use the
new expression if you want an object to exist after the function that
creates it returns.
For example, suppose you have another class called MySystem, you do this in
Java:
MySystem sys = new MySystem();
Polynomial poly = sys.createNew();
It works if you have the method createNew() in class MySystem:
Polynomial createNew() {
return new Polynomial();
}
But in C++, if you write:
MySystem sys;
Polynomial* p = sys.createNew();
you must have the mothod createNew() in class MySystem as follows
Polynomial* MySystem::createNew()
{
return new Polynomial;
}
rather than
Polynomial* MySystem::createNew()
{
Polynomial po;
return &po; // oops! a bad-point-to-be
In C++ I'd write:
MySystem sys;
Polynomial poly; sys.CreateNew(poly); // Just set initial values
See - no new/delete required.
Avoid it where you can. It's more time efficient and if you come from
Java you don't get into memory leak trouble.
Just my .02$,
-Gernot
But you can simply write
Polynomial MySystem::createNew()
{
Polynomial po;
return po;
}
There is no need for pointers with all the trouble that they bring. If you
are worried about the cost of copying a Polynomial object then the answer is
to make that class efficiently copyable (by using smart pointers for
instance) not to avoid copying by introducing pointers.
john
Hello...? Did it occur to you that the purpose of that particular tutorial
might be to *teach* using pointers? One does not learn how to use pointers
by avoiding them.
Pointers are useful in many situations, but they are most often useful when
storing polymorphic objects in containers. That is, storing pointers to
base class objects in a vector (for example), when those pointers actually
point to dynamically created instances of derived class objects. Of course,
that's something you wouldn't tackle until later, if you're just starting on
pointers, but it's an example of where they are commonly used.
All that said, I do agree that if you don't actually *need* pointers, don't
bother using them. You'll find out soon enough if there's a case where you
*do* need a pointer. (And just because a function you're calling requires a
pointer as a parameter, doesn't mean that you have to pass it a pointer
variable...you more likely want to pass the address of an existing object.)
At some point, you'll also want to look at using "smart" pointers. They
really help make code better in those cases where you *do* need pointers.
-Howard
...depending on what you call "better" code. But, I agree, there's
situations where smarties are more appropreate than simple pointers...
-Gernot
Honestly. Not a good idea.
A better idea is to get a book. There are so many pitfalls and
things to know in C++, that you can't discover them on your own
without major frustration.
--
Karl Heinz Buchegger
kbuc...@gascad.at
What if the type of object to be created is not known until run-time?
What if the number of objects to be created is not known until run-time?
At the lowest level I believe the new operator would be required.
Of course at a higher level one could use abstractions to avoid having to
explicitly use new and delete.
Such an object has it's lifetime managed by the programmer. What's your
point?
I interpreted your statement to mean that one should *only* use new for the
purposes of managing an objects lifetime.
I suggest that another purpose for using new is to defer the decision as to
which type of object to create to run-time.
It is true that the object will have its lifetime managed by the programmer but
the responsibility for lifetime management might be a consequence rather than a
goal.
void DoSomething(const string& typeIndicator)
{
Base* base = SomeFactoryFunction(typeIndicator);
delete base;
}
In this case the lifetime of the object presumably created with new is
identical to that of a variable with automatic storage duration. The need to
explicitly manage the lifetime of the object seems to be a consequence that
resulted from the need to delay the decision as to which kind of object to
create until run-time.
My only point is that lifetime management in one case might be exactly what is
desired whereas in another case it might just be a "side-effect".
I'm afraid you've lost me. I need a practical example of how a pointer could
be used without making it necessary to manage an object's lifetime. Dynamic
typing does make it necessary so as an example it isn't good enough.
True, you need a pointer or reference there. A reference is often
a solution if you need either one of N possible globals.
i.e.
base& get1() { static der1 r; return r; }
base& get2() { static der2 r; return r; }
base& the_chosen = runtime_cond() ? get1() : get2();
> What if the number of objects to be created is not known until run-time?
std::vector<type>, std::list<type>, std::deque<type>
> At the lowest level I believe the new operator would be required.
It's often used, including array new[], and placement new(here). But
the first example shows there are alternatives. And even where you
use new, it's bet used indirectly - e.g. as part of a std:: class.
BTW, even if you use new directly, avoid the need for a matching
delete. Use a smart pointer instead, e.g. boost::scoped_ptr.
Regards,
Michiel Salters
Easy. Make it point to something that's not on the heap.
class Base { /*...*/};
class D1: public Base{/*...*/};
class D2: public Base{/*...*/};
/* etc. */
void DoSomething(int typeIndicator)
{
D1 d1;
D2 d2;
/* etc. */
Base * p=0;
switch (typeIndicator)
{
case 1: p = &d1; break;
case 2: p = &d2; break;
/*...*/
}
assert(p);
p->doSomething();
// note the absence of "delete p;"
}
> Dynamic
>typing does make it necessary so as an example it isn't good enough.
>
>
--
Richard Herring
Or, roll your own smart pointer class, which is a trivial thing to do,
with the benefit of totally controlling what's in the smart ptr class
(behaivour, etc), and without the hassle of importing another library
into the already muddled mix of libraies one have to deal with.
RCS