Passing newly allocated data directly to a function

When learning different languages, I often saw objects posted on the fly, most often in Java and C #, for example:

functionCall(new className(initializers));

I understand that this is completely legal in memory-driven languages, but can this method be used in C ++ without causing a memory leak?

+5
source share
8 answers

Your code is valid (if the functionCall () function actually guarantees that the pointer will be deleted), but it is fragile and will cause the audio signals to go blank in the heads of most C ++ programmers.

There are several problems in the code:

  • , ? ? , . , , -, . , , , , , delete , !
  • , , . , : functionCall(new className(initializers), new className(initializers)); , , (, , , , ). functionCall .

( ) , , , ​​( ):

className* p = new className(initializers);
functionCall(p);
delete p;

. , functionCall ? p . / , , . , FunctionCall, ? , . . .

, :

boost::shared_ptr<className> p = boost::shared_ptr<className>(new className(initializers));
functionCall(p);

. shared_ptr , . , std::auto_ptr, shared_ptr , .

, , , , - . , .

, , , . RAII.

className , , new . . , , , , :

functionCall(className(initializers));

++ . std::vector - . new. .

+12

, . ++.

+6

.

"" functionCAll(). , , . , , - .

+5

++ .
.

new, , , . - (. ).

// No need for new or memory management just do this
functionCall(className(initializers));

// This assumes you can change the functionCall to somthing like this.
functionCall(className const& param)
{
    << Do Stuff >>
}

const, :

calssName tmp(initializers);
functionCall(tmp);

functionCall(className& param)
{
    << Do Stuff >>
}
+3

, , , -. , , .

, , clea; .

void functionCall(std::auto_ptr<className> ptr);

void functionCall(className* ptr);

, , ptr, .

+1

, , ++.

, , , , .

0

, . , ,

new T();

++ - T *, T ( # T() T).

0

All Articles