gpt4 book ai didi

c++ - 是否可以将 "fill"函数参数(默认为 null)与对象一起使用?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:10 25 4
gpt4 key购买 nike

假设我有这个方法:

bool match( /* some optional parameter */ );

这将进行一些字符串模式匹配,我想允许它被赋予一个可选参数,当方法 match() 返回 true,这样的事情可能吗?

在 PHP 中我可以这样做:

public function match( Match &$match = null ) {
if( someMatchingRoutineMatched() ) {
$match = new Match();
return true;
}

return false; // $match will stay null
}

然后像这样调用它:

// $test is some instance of the class that implements match()
// I don't have to declare $m up front, since it will be filled by reference
if( $test->match( $m ) ) {
// $m would be filled with an instance of Match
}
else {
// $m would be null
}

在 C++ 中有类似的东西吗?

我有点让它与以下一起工作

bool match( Match*& match ) {
if( /* something matches */ ) {
match = new Match;
return true;
}

return false;
}

...然后像这样调用它:

Match* m = nullptr; // I wish I wouldn't have to declare this upfront as a nullptr
if( test.match( m ) ) {
// a match occured, so m should no longer be a null pointer
// but let's just make sure
if( m != nullptr ) {
// do something useful with m and afterwards delete it
delete m;
}
}

...然而,这一切感觉有点麻烦。此外,我似乎不允许将参数设为可选,例如:

bool match( Match*& match = nullptr );

... 因为,我相信,引用不允许为 null,对吗?

我希望您能看到我正在努力实现的目标,并且希望您能就我如何实现我的目标提供一些见解,如果有可能的话,那就是。

最佳答案

invalid initialization of non-const reference of type 'Match*&' from an rvalue of type 'Match*'

Match*& match = nullptr 是不允许的,因为对非常量的引用无法绑定(bind)到临时对象,并且在此处传递 nullptr 会创建一个临时的 Match*


您可以返回指针而不是传递对非常量的引用:

Match* match() {
if( /* something matches */ ) {
return new Match;
}

return nullptr;
}

现在 nullptr 返回值表示没有匹配,非 nullptr 表示找到匹配:

if( Match* m = test.match() ) { // nullptr means false, non-nullptr means true
if( m != nullptr ) { // always true here
// do something useful with m and afterwards delete it
delete m;
}
}

或者您可以像@DanMašek 提到的那样使用重载:

bool match() {
Match* m = nullptr;
bool result = match(m);
delete m; // deleting a nullptr is a no-op
return result;
}

最后但同样重要的是,强制使用-unique_ptr-over-raw-owning-pointer,所以你不必担心delete,而且很清楚无需阅读 match 的文档,无论返回的指针是拥有还是非拥有:

unique_ptr<Match> match() {
if( /* something matches */ ) {
return make_unique<Match>( /* constructor arguments */ );
}

return nullptr;
}

if( auto m = test.match() ) { // m deduced to be of type unique_ptr<Match>
if( m != nullptr ) { // always true here
// do something useful with m and afterwards delete it
// no need to delete explicitly
}
}

关于c++ - 是否可以将 "fill"函数参数(默认为 null)与对象一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36116521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com