Create an untitled object in C ++

In Java, you can do the following:

function(new Parameter());

In C ++, I know what I can do:

Parameter p;
function(p);

But is it possible to do something like:

function(Parameter p);

in c ++?

+4
source share
2 answers

Yes. Compared to Java, you need to decide whether you want to create it on the stack or on the heap. The former may have semantics of values ​​(behaves as int-copy / moves as int, has no polymorphic behavior), while the latter will have reference semantics (refers to a single instance of an object, may behave polymorphically, copy by cloning). *

void ref( const X& x )       { x.do(); } // Reference semantics
void ptr( const X* const x ) { x->do();} // Reference semantics
void val( const X x )        { x.do(); } // Value semantics

int main()
{
    ref( X{} );     // Created on the stack
    ptr( new X{} ); // Created on the heap, but leaks!
    val( X{} );     // Created on the stack, moved rather than copied if available

    auto x = X{};   // Created on the stack
    ref( x );
    ptr( &x );
    val( x ); // Makes a copy of the object

    auto p = std::make_unique<X>(); // Created on the heap, doesn't leak
    ref( *p );
    ptr( p.get() );
    val( *p ); // Makes a copy of the object
}

* , . ., , CppCon17 . , , .

+5

, . , , Java.

:

function(Parameter());

, :

function(std::string("hello"));

, , , Java, ++:

function(new Parameter());

Parameter , . .

+5

Source: https://habr.com/ru/post/1689066/


All Articles