gpt4 book ai didi

c++ - 不可变全局对象应该声明为 'const my_result_t BLAH;' 还是 'extern const my_result_t BLAH;' ?

转载 作者:太空狗 更新时间:2023-10-29 21:31:30 26 4
gpt4 key购买 nike

首先,一些激励人心的背景信息;我正在试验将错误代码(从函数返回)表示为超轻量级人类可读字符串而不是枚举整数的想法,如下所示:

#include <string.h>

/** Ultra-lightweight type for returning the success/error status from a function. */
class my_result_t
{
public:
/** Default constructor, creates a my_result_t indicating success */
my_result_t() : _errorString(NULL) {/* empty */}

/** Constructor for returning an error-result */
my_result_t(const char * s) : _errorString(s) {/* empty */}

/** Returns true iff the result was "success" */
bool IsOK() const {return (_errorString == NULL);}

/** Returns true iff the result was an error of some type */
bool IsError() const {return (_errorString != NULL);}

/** Return a human-readable description of the result */
const char * GetDescription() const {return _errorString ? _errorString : "Success";}

/** Returns true iff the two objects are equivalent */
bool operator ==(const my_result_t & rhs) const
{
return _errorString ? ((rhs._errorString)&&(strcmp(_errorString, rhs._errorString) == 0)) : (rhs._errorString == NULL);
}

/** Returns true iff the two objects are not equivalent */
bool operator !=(const my_result_t & rhs) const {return !(*this==rhs);}

private:
const char * _errorString;
};

my_result_t SomeFunction()
{
FILE * fp = fopen("some_file.txt", "r");
if (fp)
{
fclose(fp);
return my_result_t(); // success!
}
else return my_result_t("File not Found");
}

int main(int, char **)
{
printf("SomeFunction returned [%s]\n", SomeFunction().GetDescription());
return 0;
}

...这个想法是,无需在某处维护“官方”错误代码的集中注册表,任何函数都可以简单地返回一个以人类可读的方式描述其特定错误条件的字符串。由于 sizeof(my_result_t)==sizeof(const char *),这应该不会比传统的 return-an-integer-error-code 约定效率低很多,例如POSIX 喜欢用。 (当然,我必须小心不要返回指向临时字符缓冲区的指针)

...所有这些都运行良好;我的问题涉及后续的改进,即为某些常见错误类型创建一些全局 my_result_t 定义,例如:

const my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
const my_result_t RESULT_ACCESS_DENIED("Access Denied");
const my_result_t RESULT_BAD_ARGUMENT("Bad Argument");
const my_result_t RESULT_FILE_NOT_FOUND("File not Found");
[...]

... 这样,SomeFunction() 的作者就可以返回 RESULT_FILE_NOT_FOUND; 而不是被要求输入自定义错误字符串并冒拼写错误、与其他函数的相同类型错误的结果字符串等。

我的问题是,声明这些通用/全局结果代码的运行时效率最高的方法是什么?

一种方法是使它们成为“单例对象”,如下所示:

// my_result_t.h  
extern const my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
extern const my_result_t RESULT_ACCESS_DENIED("Access Denied");
extern const my_result_t RESULT_BAD_ARGUMENT("Bad Argument");
extern const my_result_t RESULT_FILE_NOT_FOUND("File not Found");

// my_result_t.cpp
const my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
const my_result_t RESULT_ACCESS_DENIED("Access Denied");
const my_result_t RESULT_BAD_ARGUMENT("Bad Argument");
const my_result_t RESULT_FILE_NOT_FOUND("File not Found");

... 或者换一种方式,就是将以下内容简单地放在中央头文件中:

// my_result_t.h  
const my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
const my_result_t RESULT_ACCESS_DENIED("Access Denied");
const my_result_t RESULT_BAD_ARGUMENT("Bad Argument");
const my_result_t RESULT_FILE_NOT_FOUND("File not Found");

...后一种方法似乎工作正常,但我不是 100% 确信这样做是符合犹太教规的;一方面,这意味着例如RESULT_OUT_OF_MEMORY 是每个翻译单元中的一个单独对象,这似乎可能会给链接器带来压力以进行重复数据删除,甚至调用可以想象的未定义行为(我不确定这里如何应用一个定义规则)。另一方面,使用“外部”方法意味着 my_result_t 对象的实际内容仅在编译 my_result_t.cpp 时可供优化器使用,而不是在编译任何引用这些对象的其他函数,这意味着优化器可能无法进行内联优化。

从正确性的角度来看,一种方法是否比另一种方法更好,同时也有助于优化器使代码尽可能高效?

最佳答案

Const 命名空间作用域变量应该有默认的内部链接,所以在头部写const my_result_t RESULT_XXX; 是正确的:

The const qualifier used on a declaration of a non-local non-volatile non-template non-inline variable that is not declared extern gives it internal linkage. This is different from C where const file scope variables have external linkage.

此外,在函数中使用外部符号很可能不会阻止它进行内联优化,因为编译器会在适当的位置解压缩函数,并以原样保留任何外部符号。这些符号然后由链接器解析。然而,编译器的实现可能会有所不同,因此对此没有明确的说法。也就是说,使用 extern const 很可能不会对内联优化造成任何麻烦。 (我尝试使用 msvc,使用 __inline 关键字提示内联,发出的程序集显示 SomeFunction() 已内联)。

我建议使用 extern const 方法,因为每个结果对象只有一个实例。

下面是我的原始答案,如果你使用 c++ 17(使用 extern const 你将不得不写两次:定义和声明,但如果你使用 内联变量)


C++ 17 附带了您需要的一些功能。本质上,我们可以使用 string_viewconstexprinline 变量构建 my_result_t 类。我对你的代码做了一些修改:

// ErrorCode.h

#pragma once
#include <string_view>
/** Ultra-lightweight type for returning the success/error status from a function. */
class my_result_t
{
public:
/** Default constructor, creates a my_result_t indicating success */
constexpr my_result_t() : _errorString{} {/* empty */ }

/** Constructor for returning an error-result */
constexpr my_result_t(const char* s) : _errorString(s) {/* empty */ }

/** Returns true iff the result was "success" */
constexpr bool IsOK() const { return (_errorString.data() == nullptr); }

/** Returns true iff the result was an error of some type */
constexpr bool IsError() const { return (_errorString.data() != nullptr); }

/** Return a human-readable description of the result */
constexpr std::string_view GetDescription() const { return _errorString.data() ? _errorString : "Success"; }

/** Returns true iff the two objects are equivalent */
constexpr bool operator ==(const my_result_t& rhs) const
{
return _errorString.data() ? ((rhs._errorString.data()) &&
(_errorString == rhs._errorString)) : (rhs._errorString.data() == nullptr);
}

/** Returns true iff the two objects are not equivalent */
constexpr bool operator !=(const my_result_t& rhs) const { return !(*this == rhs); }

private:
std::string_view _errorString;
};

inline constexpr my_result_t RESULT_SUCCESS{};
inline constexpr my_result_t RESULT_OUT_OF_MEMORY("Out of Memory");
inline constexpr my_result_t RESULT_ACCESS_DENIED("Access Denied");
inline constexpr my_result_t RESULT_BAD_ARGUMENT("Bad Argument");
inline constexpr my_result_t RESULT_FILE_NOT_FOUND("File not Found");

// main.cpp

#include "ErrorCode.h"
#include <iostream>

inline my_result_t SomeFunction()
{
FILE* fp = fopen("some_file.txt", "r");
if (fp)
{
fclose(fp);
return RESULT_SUCCESS; // success!
}
else return RESULT_FILE_NOT_FOUND;
}

int main() {
std::cout << SomeFunction().GetDescription();
return 0;
}

Compiler explorer link

在代码中,每个翻译单元共享相同的结果对象,因为:

An inline function or variable with external linkage (e.g. not declared static) has the following additional properties:

1) It must be declared inline in every translation unit.

2) It has the same address in every translation unit.

并且它不会影响使用对象的函数内联,因为它们本质上只是编译时常量!

唯一的缺点是 string_view 的大小更大(大约是 const char 指针的两倍,具体取决于实现)。然而,这可以通过实现 constexpr “strcmp” 函数来避免:

constexpr bool strings_equal(char const* a, char const* b) {
return a == nullptr ? (b == nullptr) : (b != nullptr && std::string_view(a) == b);
}

然后您可以愉快地在结果类中使用 const char * 而不是 string_view!

关于c++ - 不可变全局对象应该声明为 'const my_result_t BLAH;' 还是 'extern const my_result_t BLAH;' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57967210/

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