C ++将指针传递到临时对象(堆上)到函数的方式? [英] C++ Ways to pass a pointer to a temporary object (on the heap) to a function?
问题描述
我有一个函数,它接受一个指向自定义类的对象的指针(实际上是指向一个基类的指针,这样多态可以工作)。然而,在呼叫例程中,为了该呼叫的目的,该对象是唯一需要的,即是临时的。例如像这样:
I've got a function that takes a pointer to an object of a custom class (actually pointers to a base class such that polymorphism works). Within the calling routine this object however is exclusively needed for the purpose of this call, i.e. is temporary. For example like this:
class A { /** stuff */ };
class B : public A { /** stuff */ };
void doSomething( const A* const _p ) { /** stuff */ }
void callingRoutine()
{
A* tempPointer = new B;
doSomething( tempPointer );
delete tempPointer;
}
现在,因为我真的只需要 doSomething
的调用中有> B ,有没有办法在一行?正在做
Now, since I really only need the object of type B
within the call to doSomething
, is there a way to do it in one line? Doing
doSomething( new B );
会创建内存泄漏(valgrind说)。或
creates memory leaks (valgrind says so). Or would
doSomething( &B );
后者编译但是给出关于将指针传递给临时对象的警告。这是我想做的,但是这样会安全吗?
be the recommended way? The latter compiles but gives warnings about passing pointers to temporary objects. This is what I want to do, but would it be safe this way?
推荐答案
>
The cleanest way is to do
B b;
doSomething(&b);
但是你真正应该写什么取决于 doSomething
函数。如果在 callRoutine
结尾处破坏 b
很好,那么这是更快更干净的方法,因为在堆栈上的分配速度快于 new
,并且不要求您之后删除 b
。
But what you really should write depends of what the doSomething
function does. If it's fine to destruct b
at the end of callingRoutine
, then it's the faster and cleaner way to do this, because allocating on the stack is faster than new
and does not require you to delete b
afterwards.
这篇关于C ++将指针传递到临时对象(堆上)到函数的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!