开发者

c++ how to ? function_x ( new object1 )

Hi i want to do the next

instead of

MyClass object;
 function_x (object);

i want to

function_x ( new object );

so what will be the structure of the MyClass to be able to do that .. if i just compiled it , it gives me a compile time err开发者_Go百科or


answer function_x (MyClass() )

New Edit thanks for the quick answers.. i did ask the wrong Question i should have asked how

temporary variables created in C++ and the answer


new is called on classes, not objects. And it returns a pointer, so unless function_x accepts a pointer, this is impossible.

You can do this though:

void function_y(MyClass* ptr)
{
  // Do something
}

// Then call
function_y(new MyClass);

Note a few things about this:

  1. The default constructor of MyClass is called when it's created
  2. function_y must keep the pointer in some accessible place to avoid a memory leak

Is this what you need, or something else?


new object returns object*, so the signature for function_x should be:

void function_x(object* obj) {
}

And you can only call operator new on a class, not instances of a class.


As per edit, if you want to create a temporary object you can like this:function_x (MyClass ()); . Note that you can not modify this temporary object so your function_x should take this parameter by const-reference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜