[英]Objects as default values in c++
is there a way to have a default Object for parameters in C++ functions? 有没有办法在C ++函数中有参数的默认对象? I tried
我试过了
void func(SomeClass param = new SomeClass(4));
and it worked. 它起作用了。 However how would I am I supposed to know wheter I have to free the allocated memory in the end?
但是我怎么会知道我到底要释放分配的内存呢? I would like to do the same without pointers, just an Object on the stack.
我想在没有指针的情况下做同样的事情,只是堆栈上的一个Object。 is that possible?
那可能吗?
void func(SomeClass param = new SomeClass(4));
This can't work because new returns a pointer 这不起作用,因为new返回一个指针
void func(SomeClass param = SomeClass(4));
should work and the object doesn't need to be freed. 应该工作,不需要释放对象。
You almost had it but you don't need the new
keyword. 你几乎拥有它,但你不需要
new
关键字。
void func(SomeClass param = SomeClass(4));
This method has the advantage over using new
in that it will be automatically deleted at the end of a call so no memory management is needed. 此方法优于使用
new
,因为它将在调用结束时自动删除,因此不需要内存管理。
An alternative is to use shared pointers. 另一种方法是使用共享指针。
You could use overloading: 你可以使用重载:
void func(const SomeClass&) const;
void func() const {
SomeClass* param = new SomeClass(4);
func(param);
delete param;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.