- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
首先,一些激励人心的背景信息;我正在试验将错误代码(从函数返回)表示为超轻量级人类可读字符串而不是枚举整数的想法,如下所示:
#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_view
、constexpr
和 inline
变量构建 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;
}
在代码中,每个翻译单元共享相同的结果对象,因为:
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/
标记为家庭作业,因为这是我写的期中问题,但我不明白答案。我被要求在以下语句中解释每个 const 的用途: const char const * const GetName() const { ret
const int* const fun(const int* const& p) const; 我试图弄清楚这个给定函数原型(prototype)的输入参数。我在这两个之间争论,不确定哪个是正确的。
下面的代码用于在同时存在 const 和非 const getter 时减少代码重复。它从非 const 创建 const 版本。我搜索了一下,很多人说我应该从 const 创建非 const 版本。
据我所知,TypeScript 查看了 const string变量作为一个不可变的类型变量,只有那个值,没有其他可能的值。一直以为加as const那是多余的。 为什么我在示例的第二部分得到以下内容
我有一个具有以下签名的方法: size_t advanceToNextRuleEntryRelatedIndex( size_t index, size_t nStrings, char const
首先,有什么区别: (1) const char* (2) char const* (3) const char const* 我相当确定我完全理解这一点,但我希望有人能具体地给我一个句子,这样它就会
这里是新手! 我正在阅读一段代码,我看到作者经常写一个成员函数作为 const int func (const scalar& a) const // etc 你看这里有三个const,现在我明白了中
我总是搞乱如何正确使用 const int*、const int * const 和 int const *。是否有一套规则来定义你可以做什么和不能做什么? 我想知道在赋值、传递给函数等方面所有该做和
我见过人们将 const 用作函数参数的代码。使用 const* 与 const * const 有什么好处?这可能是一个非常基本的问题,但如果有人能解释一下,我将不胜感激。 Bool IsThisN
我总是搞乱如何正确使用 const int*、const int * const 和 int const *。是否有一套规则来定义你可以做什么和不能做什么? 我想知道在赋值、传递给函数等方面所有该做和
这个问题在这里已经有了答案: What is the difference between const int*, const int * const, and int const *? (23 个
如果引用的对象不是 const 对象,那么引用“const”关键字的目的是什么? r1 和 r2 的作用(如下)有什么不同吗? int i = 42; // non const object cons
friend 让我解释原因 const const const const const int const i = 0; 是有效的语法。我拒绝对这个话题有任何想法。虽然我很好奇它是否只是语法问题? 编
我总是搞砸如何正确使用 const int*、const int * const 和 int const *。是否有一套规则来定义你能做什么和不能做什么? 我想知道在分配、传递给函数等方面的所有注意事
常量在 const char* push(const char * const &&_data); 表示无法更改引用的内容。为什么我不能将 const char* 传递给 push? 最佳答案 您的代
我有一个关于在函数参数中涉及指针的最佳实践以及它们是否应该指定为 *const 的问题或 const *const .我知道对于 const 的使用或过度使用存在不同的意见。 ,但至少有一些用途是捕捉
我目前正在为我的类(class)写一个作业,它应该充当一个非常基本的外壳。我快完成了,但是我遇到了 execvp 和我的参数字符数组的问题。这是我的代码的一小段。 //Split the left c
所以,我知道了char const *、char * const 和char const * const 之间的区别。那些是: char* the_string : I can change the
我正在运行一些示例程序以重新熟悉 C++,我遇到了以下问题。首先,这里是示例代码: void print_string(const char * the_string) { cout << t
我正在为系统中的编译错误而苦苦挣扎,这是代码 struct Strless : public binary_function { public : bool operator()(cons
我是一名优秀的程序员,十分优秀!