Weird trick.

Started by
22 comments, last by thedevdan 19 years, 7 months ago
class SomeClass
{
public:
   SomeClass(int lots, int of, int needed, int parameters);
...
};

SomeClass MakeSomeClass(int lots, int of, int needed, int parameters)
{
   SomeClass someClass(lots, of, needed, parameters);
   return someClass;
}




If you don't see what I'm doing, I'm just trying to create a short-lived object without having to use new. Is this an abomination (or is it just too slow)? EDIT: Clarity. [Edited by - thedevdan on September 13, 2004 8:06:00 PM]
Not giving is not stealing.
Advertisement
You don't have to use new to allocate memory for a class (or it's variables).

/MindWipe
"To some its a six-pack, to me it's a support group."
This doesn't replicate new (doesn't allocate), and a normal constructor call can be used instead of this in normal situations.

i.e
SomeClass s(...);
//
s = SomeClass(...);
Actually, this is useful where SomeClass is a templated type and the template arguments can be inferred from the parameters of the make function, as per std::pair and make_pair.
The return statement is bogus. Once executed, the stack frame
is out of scope and the returned object may be garbage bits.

Regards,
Quote:Original post by Chris Hare
...a normal constructor call can be used instead of this in normal situations....


Why didn't I think of that? [embarrass]

Well, at least they're equivelant.
Not giving is not stealing.
Quote:Original post by Anonymous Poster
The return statement is bogus. Once executed, the stack frame
is out of scope and the returned object may be garbage bits.

Regards,


Actualy I was kinda thinking something like that could happen.

/MindWipe
"To some its a six-pack, to me it's a support group."
Quote:Original post by MindWipe
Quote:Original post by Anonymous Poster
The return statement is bogus. Once executed, the stack frame
is out of scope and the returned object may be garbage bits.

Regards,


Actualy I was kinda thinking something like that could happen.

/MindWipe


No, it returns by value, not by reference.
Not giving is not stealing.
This is a godsend with templated types. Instead of
std::pair<std::vector<std::vector<int> >, std::vector<std::vector<int> > >(a, b);
you wrtie
std::make_pair(a, b);
Quote:Original post by Chris Hare
This is a godsend with templated types. Instead of
std::pair<std::vector<std::vector<int> >, std::vector<std::vector<int> > >(a, b);
you wrtie
std::make_pair(a, b);


Thanks. [smile]

But my way requires an extra temporary to be created.
Not giving is not stealing.

This topic is closed to new replies.

Advertisement