Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么将nullptr馈送到std::ostream会从操作系统产生信号11(也称为分段错误),我该如何处理它?_C++_Unit Testing_C++11_Iostream_Nullptr - Fatal编程技术网

C++ 为什么将nullptr馈送到std::ostream会从操作系统产生信号11(也称为分段错误),我该如何处理它?

C++ 为什么将nullptr馈送到std::ostream会从操作系统产生信号11(也称为分段错误),我该如何处理它?,c++,unit-testing,c++11,iostream,nullptr,C++,Unit Testing,C++11,Iostream,Nullptr,我有一个Date类,它有一个Date::print方法,我正在尝试测试它。方法本身定义为 void Date::print(std::ostream *printStream) const { invariant(); *printStream << day_ << '.' << month_ << '.' << year_; } 有效日期通过测试,没有问题,但是测试nullptr会产生分段错误。我应该如何修改方法定义来处理

我有一个
Date
类,它有一个
Date::print
方法,我正在尝试测试它。方法本身定义为

void Date::print(std::ostream *printStream) const
{
  invariant();
   *printStream << day_ << '.' << month_ << '.' << year_;
}

有效日期通过测试,没有问题,但是测试
nullptr
会产生分段错误。我应该如何修改方法定义来处理
nullptr
案例?

您正在使用
*printStream@Max Langhof Ah取消对
nullptr
的引用,这是真的。也许明智的做法是根本不执行那个特定的测试?另一个明智的做法是引用
printStream
。我认为当给定一个
nullptr
时,函数不能做任何有意义的事情,那么为什么要在语义上允许它呢?所以将
Date::print
定义为
void Date::print(std::ostream&printStream)const而不是
作废日期::打印(std::ostream*printStream)常量?是的,看起来不错。
void Unittest::print()
{
    // Creating and printing the date into string, checking if ok
    Date d(4, 5, 2000);
    std::ostringstream printStream;
    d.print(&printStream);
    QCOMPARE(printStream.str(), std::string("4.5.2000"));

    // Testing with a nullptr
    d.print(nullptr);
}