Here is my question. I have a pointer with allocated memory to some class:
这是我的问题。我有一个指针,分配给某些类的内存:
Class *pClass = new Class();
Now I want to pass this object to some function, wich will use this object just to copy it and will not modify it. The question is how to correctly pass the object?
现在我想将这个对象传递给某个函数,它将使用这个对象来复制它而不会修改它。问题是如何正确传递对象?
void someFunc (const Class &_class);
{
Class *pClassInFunc = new Class (_class);
...
}
...
someFunc (*pClass)
or
void someFunc (const Class *_class);
{
Class *pClassInFunc = new Class (*_class);
...
}
...
someFunc (pClass)
or
void someFunc (Class _class);
{
// just use _class since it's already a copy
...
}
...
someFunc (*pClass)
I've choosed the first way, but it looks strange to me, smth tells me that it's not correct. The second one looks more C-style (or not?). And the last one creates a copy in the stack, which is not desireable. So, what is the best solution? Thank you for your answers.
我选择了第一种方式,但它看起来很奇怪,smth告诉我这不正确。第二个看起来更C风格(或不?)。最后一个在堆栈中创建一个副本,这是不可取的。那么,什么是最好的解决方案?谢谢您的回答。
EDIT: just saw, I forgot * before pClassInFunc. Corrected, sorry.
编辑:刚看到,我在pClassInFunc之前忘记了*。纠正了,抱歉。
1 个解决方案
#1
4
I vote for the last approach. Design your function so that it doesn't care exactly how the calling code allocated the object. If it wants a copy, take the object by value. It makes the intentions clearer to the user.
我投票支持最后一种方法。设计你的函数,使它不关心调用代码如何分配对象。如果需要副本,请按值获取对象。它使用户的意图更清晰。
It also allows the caller to move from their object if they don't need it any more. If you were to take a reference to const
and then copy it, that wouldn't be an option (you can't move from a const
object).
它还允许调用者从他们的对象移动,如果他们不再需要它。如果你要引用const然后复制它,那就不是一个选项(你不能从const对象移动)。
If the calling code can, it should avoid dynamically allocating the object in the first place. Then, if you choose to take the argument by value, it is very simple to pass the object.
如果调用代码可以,则应该避免首先动态分配对象。然后,如果您选择按值获取参数,则传递对象非常简单。
#1
4
I vote for the last approach. Design your function so that it doesn't care exactly how the calling code allocated the object. If it wants a copy, take the object by value. It makes the intentions clearer to the user.
我投票支持最后一种方法。设计你的函数,使它不关心调用代码如何分配对象。如果需要副本,请按值获取对象。它使用户的意图更清晰。
It also allows the caller to move from their object if they don't need it any more. If you were to take a reference to const
and then copy it, that wouldn't be an option (you can't move from a const
object).
它还允许调用者从他们的对象移动,如果他们不再需要它。如果你要引用const然后复制它,那就不是一个选项(你不能从const对象移动)。
If the calling code can, it should avoid dynamically allocating the object in the first place. Then, if you choose to take the argument by value, it is very simple to pass the object.
如果调用代码可以,则应该避免首先动态分配对象。然后,如果您选择按值获取参数,则传递对象非常简单。