gpt4 book ai didi

c++ - 在静态函数中返回一个对象而不是构建它有什么好处?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:06:43 26 4
gpt4 key购买 nike

以 Qt 框架的以下文档为例,即使我的问题不是特定于 Qt 的:

https://doc.qt.io/qt-5/qversionnumber.html

你可以找到静态公共(public)成员函数:

QVersionNumber fromString(const QString &string, int *suffixIndex = nullptr)

代替:

QVersionNumber(const QString &string, int *suffixIndex = nullptr)

在构造函数列表中。

我已经在许多库 API 中看到了这种选择,但我不明白它的优势是什么以及为什么缺少该构造函数。

最佳答案

这实际上是一个很好的问题。

原因因情况而异,但涉及以下问题:

  • 构造函数的可读性如何?
  • 我是否在创建人造对象或不必要地复制条件,以便根据初始化列表编写构造函数?
  • 我的构造函数是否与旨在执行不同类型构造的构造函数有歧义?
  • 我的构造函数在做什么而不用在代码中拼出名字是否很明显?

以上所有内容都涉及一定程度的主观性。

假设的例子,猜测 QVersionNumber 的内部结构,

你会如何在初始化列表中写这个?

QVersionNumber 
QVersionNumber::fromString(const QString &string, int *suffixIndex)
{
std::optional<QVersionNumber> result;
auto first = string.begin();
auto last = string.end();
auto opt_major = maybe_extract_decimal(first, last); // modifies first
if (not opt_major.has_value())
result.emplace();
else
{
auto opt_minor = maybe_extract_decimal(first, last); // modifies first
if (not opt_major.has_value())
result.emplace(*opt_major);
else
result.emplace(*opt_minor);
}
if (suffixIndex)
*suffixIndex = int(std::difference(string.begin(), first);
return *std::move(result);
}

这当然是可能的,遵从采用专用函数对象的私有(private)构造函数。但是库的作者可能认为这太隐晦或难以维护。

关于c++ - 在静态函数中返回一个对象而不是构建它有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54805163/

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