[英]How to declare a pointer to a variable as a parameter of a function in C++?
I have a function that takes a const D3DVECTOR3 *pos
, but I have no reason to declare this beforehand. 我有一个使用
const D3DVECTOR3 *pos
的const D3DVECTOR3 *pos
,但是我没有理由事先声明。 The most logical solution to me was using new: 对我来说,最合理的解决方案是使用new:
Function(
//other parameters,
new D3DXVECTOR3(x, y, 0));
but I don't know how I would go about deleting
it, beign intitialized in a function. 但是我不知道如何
deleting
它,将其初始化为一个函数。 My next thought was to use the &
operator, like so: 我的下一个想法是使用
&
运算符,如下所示:
Function(
//other parameters,
&D3DVECTOR3(x, y, 0));
but I don't know if this is a valid way to go about doing this. 但我不知道这是否是执行此操作的有效方法。 (It doesn't get an error, but there are a lot of things that don't give errors that aren't necassarily good).
(它没有出现错误,但是很多情况下并不会产生错误,这并不是必须的)。 So should I use
new
, &
, or some other technique I'm overlooking? 因此,我应该使用
new
, &
或其他我忽略的技术吗?
It's not possible to directly invoke the address-of operator to the temporary (MSVC will tell you that this is not Standard C++ at higher warning levels, too). 不可能直接调用临时操作符的address-of运算符(MSVC会告诉您,在更高警告级别,它也不是Standard C ++)。 Except you may do
除了你可以做
Function(
//other parameters,
&(D3DXVECTOR3 const&)D3DXVECTOR3(x, y, 0));
But this is disgusting. 但这真令人恶心。 Just declare a local variable and pass its address.
只需声明一个局部变量并传递其地址即可。
I see no reason to not instantiate the object before the function call then delete it afterwards. 我认为没有理由在函数调用之前不实例化该对象,然后再将其删除。 Also worth noting,
同样值得注意的是
Function(
//other parameters,
new D3DXVECTOR3(x, y, 0));
I think this will result in a memory leak if Function does not return a pointer or deposit it into some kind of memory pool. 我认为如果Function不返回指针或将其存放到某种内存池中,将导致内存泄漏。 Hope this helps.
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.