在C++中创建一个没有名称的对象

tra*_*aww 4 c++ initialization object parameter-passing

在Java中,可以执行以下操作:

function(new Parameter());
Run Code Online (Sandbox Code Playgroud)

在C++中我知道我可以这样做:

Parameter p;
function(p);
Run Code Online (Sandbox Code Playgroud)

但有可能做类似的事情:

function(Parameter p);
Run Code Online (Sandbox Code Playgroud)

在C++中?

met*_*tal 7

是.与Java相比,您需要决定是在堆栈上还是在堆上创建它.前者可以具有值语义(行为类似于int - 副本/移动像int,没有多态行为),而后者将具有引用语义(指向相同的对象实例,可以表现多态,通过克隆复制).

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
}
Run Code Online (Sandbox Code Playgroud)

注意:如果跳过一些箍,你可以使用值语义进行多态行为.例如,请参阅Louis Dionne在CppCon17上关于运行时多态性的演讲.如果你没有跳过这些环,但尝试多态地使用一个值对象,你最终可能会遇到对象切片.


Ori*_*iBS 6

是的,你可以做这样的事情.由于这是一个临时变量,因此您无需为其命名,就像在Java中一样.

语法将是:

function(Parameter());
Run Code Online (Sandbox Code Playgroud)

如果类需要参数,您只需将其传递给临时变量构造函数:

function(std::string("hello"));
Run Code Online (Sandbox Code Playgroud)

最后,您为Java编写的内容也适用于c ++:

function(new Parameter());
Run Code Online (Sandbox Code Playgroud)

但是这会在堆上分配Parameter对象,为了避免内存泄漏,你必须在函数内删除它.但这通常是一个坏主意.