假设A,B,a,和b都是变量,的地址A,B,a,和b都是不同的.然后,对于以下代码:
A = a;
B = b;
Run Code Online (Sandbox Code Playgroud)
C和C++标准是否明确要求A=a在之前严格执行B=b?考虑到的地址A,B,a,和b都不同,编译器允许交换两个语句的执行顺序为某种目的,如优化?
如果我的问题的答案在C和C++中有所不同,我想知道两者.
编辑:问题的背景如下.在棋盘游戏AI设计中,对于优化,人们使用无锁共享哈希表,如果我们不添加volatile限制,其正确性很大程度上取决于执行顺序.
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
printf("construct ..\n");
}
~Test()
{
printf("destruct...\n");
}
};
Test Get()
{
Test t = Test();
return t;
}
int main(int argc, char *argv[])
{
Test t = Get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
控制台输出是:
$ g++ -g -Wall -O0 testdestructor.cc
$ ./a.out
Run Code Online (Sandbox Code Playgroud)
构造..
破坏...
我正在玩C++构造函数.这是我的代码:
#include <iostream>
using namespace std;
class ArrayWrapper
{
public:
// default constructor produces a moderately sized array
ArrayWrapper ()
: _p_vals( new int[ 64 ] )
, _size( 64 )
{
cout << "Default constructor: " << this << endl;
}
explicit ArrayWrapper (int n)
: _p_vals( new int[ n ] )
, _size( n )
{
cout << "Constructor: " << this << endl;
}
// move constructor
ArrayWrapper (ArrayWrapper&& other)
: _p_vals( other._p_vals )
, _size( other._size …Run Code Online (Sandbox Code Playgroud) 我真的很困惑....是否Type t = Type()调用了复制构造函数或者没有?
我问,因为当我尝试:
#include <iostream>
class Test
{
public:
Test(Test const &) { std::cout << "hello"; }
Test() { }
};
int main()
{
Test t = Test();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
没有输出,但当我改变它
#include <iostream>
class Test
{
Test(Test const &) { std::cout << "hello"; }
public:
Test() { }
};
int main()
{
Test t = Test();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我明白了:
error C2248: 'Test::Test' : cannot access private member declared in class 'Test'
Run Code Online (Sandbox Code Playgroud)
这没有意义(特别是因为这是一个调试版本).
即便这样编译! …
我是C++的初学者,我正在使用的资源说下面的语句d3 = d1 + d2; 调用以下内容:
我不明白为什么在将结果分配给先前声明的变量时调用复制构造函数以及为什么调用2个构造函数.
运营商如下:
date& date::operator=(const date& other)
{
cout << "Date assignment op" << endl;
if (this!=&other){
day=other.day;
month=other.month;
year=other.year;
}
return *this;
}
date date::operator+(const date& other) const
{
cout << "Date Operator + called" << endl;
date temp;
temp.day=day+other.day;
temp.month=month+other.month;
temp.year=year+other.year;
return temp;
}
Run Code Online (Sandbox Code Playgroud)