Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object without a name in C++

In Java it is possible to do the following:

function(new Parameter());

In C++ I know that I could do:

Parameter p;
function(p);

But is it possible to do something like:

function(Parameter p);

in C++?

like image 246
trafalgarLaww Avatar asked Nov 10 '17 13:11

trafalgarLaww


2 Answers

Yes. By comparison to Java, you need to decide if you want to create it on the stack or on the heap. The former can have value semantics (behaves like an int -- copies/moves like an int, no polymorphic behavior), while the latter will have reference semantics (refers to the same object instance, can 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 heap object on the stack
}

Note: You can have polymorphic behavior with value semantics if you jump through some hoops. See, for instance, Louis Dionne's talk at CppCon17 on Runtime Polymorphism. If you don't jump through these hoops but try to use a value object polymorphically, you can end up with object slicing.

like image 53
metal Avatar answered Oct 19 '22 23:10

metal


Yes you could do such a thing. As this is a temporary variable you don't need to name it, just as you did in Java.

The syntax will be:

function(Parameter());

If the class need parameter you just pass it to the temporary variable constructor:

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

And finally, what you wrote for Java will work in c++ as well:

function(new Parameter());

But this will allocate the Parameter object on the heap, and in order to avoid memory leak, you will have to delete it inside function. But this is usually a bad idea.

like image 7
OriBS Avatar answered Oct 19 '22 23:10

OriBS