【问题标题】:Formatting `nullptr` on out stream as hexadecimal address, instead of `0`将输出流上的“nullptr”格式化为十六进制地址,而不是“0”
【发布时间】:2020-08-12 12:18:52
【问题描述】:

如何在输出流上格式化任何类型的空指针,最好包括立即的nullptr,以便它像0x000000000000 甚至只是0x0 一样打印出来,但类似于地址值而不是无意义的@987654324 @ 或 terminate 或任何非地址类? //(nil)(null) 如果不使用printf,我也可以接受。

【问题讨论】:

  • 你能使用 C++20 的特性吗?
  • 零值,当转换为指针时,会给出一个空指针常量。所以输出一个零实际上是有道理的。如果ptr 是一个指针,你总是可以做if (!ptr) std::cout << "0x0"

标签: c++ formatting cout nullptr


【解决方案1】:

您可以制作一个指针格式化程序,它可以按照您喜欢的任何方式进行格式化。

例如:

#include <cstdint>
#include <iomanip>
#include <ios>
#include <iostream>
#include <sstream>
#include <string>

static auto Fmt(void const* p) -> std::string {
    auto value = reinterpret_cast<std::uintptr_t>(p);
    constexpr auto width = sizeof(p) * 2;
    std::stringstream ss;
    ss << "0x" << std::uppercase << std::setfill('0') << std::setw(width) << std::hex << value;
    return ss.str();
}

int main() {
    char const* p = nullptr;
    std::cout << Fmt(p) << "\n";
    p = "Hello";
    std::cout << Fmt(p) << "\n";
}

【讨论】:

  • 另外,请注意 C++20 std::format 存在。
  • @Eljay 看来 足以满足此解决方案。如果我遗漏了其他标题的用途,请详细说明。
  • @Multifix • &lt;cstdint&gt; 用于 std::uintptr_t。 &lt;string&gt; 用于 std::string。 &lt;sstream&gt; 用于 std::stringstream。 &lt;ios&gt; 为 std::hex。
【解决方案2】:

你可以为空指针重载

#include <iostream>

struct Foo {
    void bar() {}
};

std::ostream& operator<<(std::ostream& stream, void *p) {
    return stream << 0 << 'x' << std::hex << reinterpret_cast<size_t>(p) << std::dec;
}

int main() {
    Foo foo;
    Foo *p = &foo;

    std::cout << p << std::endl;
    p = nullptr;
    std::cout << p << std::endl;
}

或者添加一个更灵活的包装器,因为您可以使用这两种方法,但需要更多的输入。

#include <iostream>

struct Foo {
    void bar() {}
};

struct Pointer_wrapper {
    void *p_;
    explicit Pointer_wrapper(void *p) :p_(p) {}
};

std::ostream& operator<<(std::ostream& stream, const Pointer_wrapper& w) {
    return stream << 0 << 'x' << std::hex << reinterpret_cast<size_t>(w.p_) << std::dec;
}

using pw = Pointer_wrapper;

int main() {
    Foo foo;
    Foo *p = &foo;

    std::cout << pw(p) << std::endl;
    p = nullptr;
    std::cout << pw(p) << std::endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多