我偶然发现了一些代码,其中typedef关键字位于类型和别名之间,如in
int typedef INT;
Run Code Online (Sandbox Code Playgroud)
它编译为gcc和clang(实例).我不太了解标准.所以我的问题是:这个标准符合吗?我可以依靠编译器来支持它吗?
这是此处讨论的后续内容.
以下代码在gcc和clang(实时演示)下编译.//1由于lambda没有捕获任何东西,因此对于该情况而言这是令人惊讶的.对于MCR2lambda返回指针本身的情况,我们得到预期的编译时错误(行// Will not compile).运算符的应用sizeof与返回指针有何不同?
#include <iostream>
#define MCR1(s) \
([]() { return sizeof(s); })()
#define MCR2(s) \
([]() { return s; })()
int main() {
auto *s= "hello world";
auto x1 = MCR1( s ); //1
auto y1 = MCR1( "hello world" );
// auto x2= MCR2( s ); // Will not compile
auto y2= MCR2( "hello world" );
std::cout << x1 << " " << y1 …Run Code Online (Sandbox Code Playgroud) 请考虑以下示例.
std::mutex mtx;
std::condition_variable cv;
void f()
{
{
std::unique_lock<std::mutex> lock( mtx );
cv.wait( lock ); // 1
}
std::cout << "f()\n";
}
void g()
{
std::this_thread::sleep_for( 1s );
cv.notify_one();
}
int main()
{
std::thread t1{ f };
std::thread t2{ g };
t2.join();
t1.join();
}
Run Code Online (Sandbox Code Playgroud)
g()"知道" f()在我想讨论的场景中等待.根据cppreference.com,g()在调用之前无需锁定互斥锁notify_one.现在在标记为"1"的行cv中将释放互斥锁并在发送通知后重新锁定它.析构函数在lock此之后立即再次释放它.这似乎是多余的,特别是因为锁定很昂贵.(我知道在某些情况下需要锁定互斥锁.但这不是这种情况.)
为什么condition_variable没有函数" wait_nolock",一旦通知到达,它就不会重新锁定互斥锁.如果答案是pthreads没有提供这样的功能:为什么不能延长提供它的pthreads?是否有实现理想行为的替代方案?
以下代码使用枚举成员m作为常量表达式,即作为模板参数.代码在gcc下编译,但不在clang(现场演示)下编译.Clang说"错误:非类型模板参数不是常量表达式".
这个问题可以通过交换行来解决// 1的A<tst<p>::m> a.因此,我的问题不是如何解决这个问题,而是哪个编译器是正确的.
template<size_t n> struct A{};
template<size_t n>
struct tst
{ enum : size_t { m= n % 15 };
template<size_t p>
void
call( tst<p> const &t2 ) {
A<t2.m> a; // 1
}
};
Run Code Online (Sandbox Code Playgroud) 我正在使用gcc在Linux下将一些旧的C++代码升级到C++ 11.在设置优先级时,我提出了以下问题.莫不是在呼叫交换到任何优势usleep与一个呼叫std::this_thread::sleep_for?在代码我说的是运行线程应该等待很短的时间.因此,我不需要任何高级功能,如打断睡眠.
以下代码包含的const版本和非const版本operator()。输出
非const运算,假
常量运算,真正的
常量运算,真正的
常量运算,真
即const版本被称为如果任一类型的对象S或是常量如果所提交的指针是常量-线// 2,// 3,// 4。现在,我希望代码// 2可以导致编译时错误,即,我希望const版本只能在const对象上调用。显然,static_assert开启is_const_v<decltype(*this)>不会起作用。还有其他想法吗?
我知道,将非常量变量转换为常量很容易。但这将使滥用至少显而易见。
#include <iostream>
#include <type_traits>
struct S
{
void
operator()( int * )
{
std::cout << std::boolalpha
<< "Non-const op, "
<< std::is_const_v<typename std::remove_reference_t<decltype(*this)> > << '\n';
}
void
operator()( int const * ) const
{
std::cout << std::boolalpha
<< "Const op, "
<< std::is_const_v<typename std::remove_reference_t<decltype(*this)> > << '\n';
}
}; …Run Code Online (Sandbox Code Playgroud) C++23 将引入if consteval. 这将在哪里使用,它与constexpr if?
这是怎么回事,标准没有提到once_flag的可移动性?我希望应用与 std::mutex 相同的参数。至少对于 gcc(4.8 版)来说,移动似乎被禁用了。如果某个编译器允许移动,那么最终可能会得到不可移植的代码。