struct foo
{
const int A;
int B;
foo() : A(10), B(20) {}
};
void main()
{
foo f1;
const_cast<int&>(f1.A) = 4; //line 1
const foo f2;
const_cast<int&>(f2.B) = 4; //line 2
}
Run Code Online (Sandbox Code Playgroud)
第1行和第2行都表现出未定义的行为吗?请问行为有所不同,如果f1和f2是shared_ptr在上面的代码中列出的类型?
我有一个第三方C库,其匿名结构类似于
typedef struct
{
...
}A;
Run Code Online (Sandbox Code Playgroud)
该文件是通过程序自动生成的,因此可以根据某些内容进行更改
现在在C++项目中,我接受上述类型的参数,例如as
void foo(const A & in)
{
...
}
Run Code Online (Sandbox Code Playgroud)
如何在定义上述函数的头文件中转发声明A?
我试过了 :
typedef struct A A;
Run Code Online (Sandbox Code Playgroud)
要么
struct A;
Run Code Online (Sandbox Code Playgroud)
并且
typedef A A;
Run Code Online (Sandbox Code Playgroud)
出于好奇.
但是,这会导致重新定义类型的编译时错误.谢谢
请考虑以下代码段,其中第一行仅用作前向声明
class A;
Run Code Online (Sandbox Code Playgroud)
然后定义新类
class B
{
vector<A> Av; //line 1
map<int, A> Am; //line 2
pair<int, A> Ap; //line 3
};
Run Code Online (Sandbox Code Playgroud)
第1行和第2行似乎没有前向声明(这可能告诉我那些容器使用指针类型的实现),其中第3行似乎不在VS2012上编译.
我的问题是标准或特定于我正在使用的编译器所规定的行为?
谢谢
我知道在 a 中,class成员是按照列出的顺序初始化的。这是否适用于将变量分组为public等private?我的困惑是,我无法弄清楚是否存在诸如private成员按照在成员之前列出的顺序进行初始化的偏好public,无论私有变量在类声明中相对于公共列出的位置如何(我知道存在这种偏见)基类成员)
请考虑以下代码段
class tmp1
{
const int a_;
const double b_;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int ver)
{
ar & a_ & b_ ;
}
public:
tmp1(const itype a , const ftype b) : a_(a), b_(b)
{}
};
Run Code Online (Sandbox Code Playgroud)
通过这样做,我可以将对象写入文件
tmp1 t1(2, 10.0);
std::string filename ="D:/Temp/demofile.txt";
std::ofstream ofs(filename);
boost::archive::text_oarchive oa(ofs);
oa<<t1;
Run Code Online (Sandbox Code Playgroud)
我想tmp1通过读取文件来构造另一个实例.理想情况下,我希望这发生在第二个构造函数中,它接受文件名并构造它.我该如何做到这一点?
我试过了
tmp1 t2(10, 100.0);
std::ifstream ifs(filename);
boost::archive::text_iarchive ia(ifs);
ia>>t2;
Run Code Online (Sandbox Code Playgroud)
但VS2012编译失败,并显示以下消息
archive/detail/check.hpp(162): error C2338: typex::value
4> \boost\boost_1_67_0\boost/archive/detail/iserializer.hpp(611) : see reference to function …Run Code Online (Sandbox Code Playgroud) 考虑
bool Fun1()
{
...
}
bool Fun2()
{
}
Run Code Online (Sandbox Code Playgroud)
在我可以拥有的主要代码中的某个地方
if(Fun1() && Fun2()) //option-1
{
}
Run Code Online (Sandbox Code Playgroud)
要么
if(Fun1() & Fun2()) //option-2
{
}
Run Code Online (Sandbox Code Playgroud)
在VS2012中似乎option-1没有确保在发生这两种功能时始终执行这两项功能option-2.具体来说,如果其中一个函数返回,false则不执行其他函数option-1.但是,整体代码要求对它们的正确行为进行评估,这是我能够实现的option-2.我想知道这种行为是否option-2可以从编译器改为编译器(也有优化级别)或由标准确保?
1) How this pointer is different from other pointers? As I understand pointers point to the memory in heap. Does that mean objects are always constructed in heap, given that there is pointer to them?
2)Can we steal this pointer in move constructor or move assignment?
c++ ×7
const ×2
boost ×1
c++14 ×1
class ×1
const-cast ×1
constructor ×1
move ×1
optimization ×1
private ×1
public ×1
shared-ptr ×1
std-pair ×1
stl ×1
structure ×1
this ×1