#include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
return std::forward<Container>(arr)[n];
}
Run Code Online (Sandbox Code Playgroud)
进行函数调用:
#include <vector>
index(std::vector {1, 2, 3, 4, 5}, 2) = 0;
Run Code Online (Sandbox Code Playgroud)
当函数调用完成时,对象std::vector {1, 2, 3, 4, 5}
将被销毁,为释放的地址赋值会导致未定义的行为。但是上面的代码运行良好,valgrind 什么也没检测到。也许编译可以帮助我制作另一个不可见的变量,例如
auto &&invisible_value {index(std::vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;
Run Code Online (Sandbox Code Playgroud)
如果我的猜测不正确,我想知道为什么为从函数返回的右值引用赋值是可行的,以及临时对象index(std::vector {1, 2, 3, 4, 5}, 2)
何时会被销毁。
这个想法起源于?Effective Modern C++?,Item3:理解decltype
。
Valgrind 现在与 macOS 12 不兼容,我尝试添加编译标志-fsanitize=address
,但出现链接错误:
Undefined symbols for architecture x86_64:
"___asan_init", referenced from:
_asan.module_ctor in main.cpp.o
"___asan_version_mismatch_check_apple_clang_1300", referenced from:
_asan.module_ctor in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)
有没有办法让 Valgrind 兼容 macOS 12?
我发现 std::array for 中有一个模板部分特化std::array<T, 0>
。
template <typename T>
struct array<T, 0> {
//...
typedef typename conditional<is_const<_Tp>::value, const char,
char>::type _CharType;
struct _ArrayInStructT { _Tp __data_[1]; };
alignas(_ArrayInStructT) _CharType __elems_[sizeof(_ArrayInStructT)];
//...
}
Run Code Online (Sandbox Code Playgroud)
那么实施的目的是std::array<T, 0>
什么?
非常感谢!
对于std::is_literal_type
和,这是相同的情况std::is_standard_layout
.
std::is_literal_type
在libc ++中的实现是
template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_literal_type
#ifdef _LIBCPP_IS_LITERAL
: public integral_constant<bool, _LIBCPP_IS_LITERAL(_Tp)>
#else
: integral_constant<bool, is_scalar<typename remove_all_extents<_Tp>::type>::value ||
is_reference<typename remove_all_extents<_Tp>::type>::value>
#endif
{};
Run Code Online (Sandbox Code Playgroud)
没有_LIBCPP_IS_LITERAL
,所以代码将是
template <typename T> struct is_literal_type : integral_constant<bool,
is_scalar<typename remove_all_extents<T>::type>::value or
is_reference<typename remove_all_extents<T>::type>::value> {};
Run Code Online (Sandbox Code Playgroud)
我写了一个演示:
#include <iostream>
using namespace std;
struct s {
int a;
char b;
long c;
};
int main(int argc, char *argv[]) {
cout << boolalpha;
cout << is_scalar_v<typename remove_all_extents<s>::type> << endl;
cout << is_reference_v<typename …
Run Code Online (Sandbox Code Playgroud)