gpt4 book ai didi

c++ - `const std::string& s = nullptr` 作为可选参数如何工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:56:00 25 4
gpt4 key购买 nike

据我所知,引用不能为空,但是当我运行这样的代码时:

#include <iostream>
#include <string>

void test(int i, const std::string& s = nullptr) {
std::cout << i << " " << s << std::endl;
}

int main() {
test(1, "test");
test(2);
}

可选参数s可以为null,构建代码。更重要的是,当 test(2) 运行时,程序会抛出异常,而不是打印一些随机字符串。

当我将 s 更改为一些基本类型(如 int)时,它无法编译,所以我认为魔法留在字符串类中,但如何呢?

而且,我如何检查 s 是否为空?如果我使用 if(s==nullptr)if(s.empty()),它无法编译。

最佳答案

test使用构造函数初始化其参数 number 5std::basic_string<char> :

basic_string( const CharT* s,
const Allocator& alloc = Allocator() );

因为它需要具体化一个临时的 ( std::string ) 来绑定(bind)到那个引用。这是因为引用必须绑定(bind)到正确类型的对象,即 std::nullptr_t不是。并且所述构造函数对传递的指针有一个 not null 约束。打电话test没有显式参数会导致未定义的行为。

非常清楚,在格式良好的 C++ 程序中没有空引用这样的东西。引用必须绑定(bind)到一个有效对象。尝试用 nullptr 初始化一个只会寻求进行转换。

std::string是一个具有明确定义的“空”状态的对象,固定版本可以简单地传入一个默认的初始化字符串:

void test(int i, const std::string& s = {}); // Empty string by default.

解决契约(Contract)违规问题后,s.empty()应该再次给出有意义的结果。

关于c++ - `const std::string& s = nullptr` 作为可选参数如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001358/

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