我的问题是由stackoverflow上的这个答案https://stackoverflow.com/a/48082010/5360439引起的。引用,Q:Howyouconvertastd::string_viewtoaconstchar*?A:Simplydoastd::string(string_view_object).c_str()togetaguaranteednull-terminatedtemporarycopy(andcleanitupattheendoftheline).不幸的是,它构造了一个新的string。我想知道是否可以简单地做,static_cast(str
我的C++03代码如下所示:#include...std::tr1::unordered_mapmystuff;...我开始怀疑如果/当我将代码转换为C++11(我猜)没有std::tr1::unordered_map但有std::unordered_map代替。所以我想出了以下技巧:namespacestd{usingnamespace::std::tr1;}...std::unordered_mapmystuff;//notr1now!...是否合法(也许禁止将内容导入到std中)?它会让移植/与C++11代码互操作变得更容易吗? 最佳答案
我的代码如下:#include#includeintmain(){for(int&v:std::vector{1,3,5,10}){std::cout据我了解,vector是prvalue,不能绑定(bind)到int&,但是这个能正常工作吗?是不是因为for范围循环只是宏扩展,会为vector创建一个临时变量? 最佳答案 根据C++ISO规范,基于范围的for循环被正式定义为等价于{auto&&__range=range_expression;for(auto__begin=begin_expr,__end=end_expr;__
如果您将externC与C++文件一起使用,是否允许在C++中未定义的已定义C行为?废话.hextern"C"{structx{intblah;charbuf[];};char*get_buf(structx*base);structx*make_struct(intblah,intsize);}some_random.cpp#include"blah.h"...x*data=make_struct(7,12);std::strcpy(get_buf(data),"hello");是在C的灵活数组成员中使用定义的行为,这样使用时定义的行为? 最佳答案
我最近偶然发现了一些奇怪的东西:将bool值转换为指针在VisualStudio2013和2015中有效,但在GCC和Clang中无效(在3.5中尝试过)。#includeusingnamespacestd;voidfoo(int*ptr){std::coutGCC中的错误:main.cpp:Infunction'intmain()':main.cpp:13:13:error:cannotconvert'bool'to'int*'forargument'1'to'voidfoo(int*)'foo(false);^我的猜测是false被转换为0,相当于NULL。用foo(true)替换
考虑以下由同事提供的代码:#include#includeintmain(){constintsize=4;return[size](){std::arraya;//*returna.size();}();}它被Clang5.0.0接受,但被GCC7.2拒绝,带星号的行的错误消息是:error:'__closure'isnotaconstantexpression哪个编译器是正确的? 最佳答案 该规则实际上很直观:任何不需要捕获的变量都指的是原始变量。[expr.prim.lambda]/11:Everyid-expressionw
这个程序:#includestructFoo{Foo(){std::cout打印Bar()~Bar()Foo()对我来说(GCC6.1、Linux、x86-64)。~Foo()永远不会被调用。这是预期的行为吗? 最佳答案 标准不包括这种情况;最严格的理解是,在具有静态存储持续时间的对象的析构函数中初始化thread_local是合法的,但允许程序继续正常完成是非法的。问题出现在[basic.start.term]:1-Destructors([class.dtor])forinitializedobjects(thatis,obje
在thisanswer,出现了以下场景:#includestructA{};structB{virtual~B(){}};structAA{};templatestructC:A,T{};intmain(){B*b=newC;AA*aa=newC;assert(dynamic_cast(b));assert(dynamic_cast(aa));//thislinedoesn'tcompile,asexpected}在g++4.8.4(Ubuntu)上,它编译并且断言通过。我的问题是,这真的合法吗?我觉得您根本不应该将dynamic_cast转换为非多态类,但我坦率地承认,我不是这里发生
通常,constexpr必须没有副作用。但是,我刚刚发现可以在抛出异常的构造函数中使用副作用。该技术可用于模拟constexpr函数的assert(),如下面的程序所示。#include#include#includestructconstexpr_precond_violated:std::logic_error{constexpr_precond_violated(constchar*msg):std::logic_error(msg){std::cerrfailed(file:"\__FILE__",line:"TO_STRING(__LINE__)")")\:(value))c
这是另一个question的后续内容关于内存重用。由于最初的问题是关于特定实现的,因此答案与特定实现有关。所以我想知道,在符合标准的实现中,将基本类型数组的内存重新用于提供的不同类型数组是否合法:这两种类型都是基本类型,因此具有普通的dtor和默认的ctor两种类型的尺寸和对齐要求相同我以以下示例代码结束:#includeconstexprintSize=10;void*allocate_buffer(){void*buffer=operatornew(Size*sizeof(int),std::align_val_t{alignof(int)});int*in=reinterpret