小编asa*_*elr的帖子

为什么抛出局部变量调用移动构造函数?

最近,我用rvalues"玩"了解他们的行为.大多数结果并没有让我惊讶,但后来我看到如果我抛出一个局部变量,就会调用移动构造函数.

在那之前,我认为移动语义规则的目的是保证只有当编译器能够检测到它不再被使用时(如在临时对象中)或者用户不承诺时,对象才会移动(并变为无效).使用它(如在std :: move中).

但是,在下面的代码中,没有这个条件,并且我的变量仍然被移动(至少在g ++ 4.7.3上).

这是为什么?

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s="blabla";
    try {
        throw s;
    }
    catch(...) {
        cout<<"Exception!\n";
    }
    cout<<s; //prints nothing
}
Run Code Online (Sandbox Code Playgroud)

c++ exception move-semantics c++11

19
推荐指数
2
解决办法
641
查看次数

C和C++编译器为以下代码提供不同的消息,为什么?

我被要求在面试中提供以下代码的输出.

int a[] = {1,2,3,4,5};
int *p = &a + 1;
printf("%d, %d", *(a+1), *(p - 1));
Run Code Online (Sandbox Code Playgroud)

我说我无法确定第二个结果,所以我没能通过采访.

当我回到家中并尝试编译代码时,g ++会报告错误,但gcc只会发出警告.打印结果为"2,5".

任何人都知道为什么C和C++编译器在这方面表现不同?

c c++

2
推荐指数
2
解决办法
368
查看次数

无法使用非成员开始和结束功能编写范围

我正在编写一个使用位板的代码.因为迭代位板的所有位是非常常见的动作,所以我决定编写一些迭代器类,并使用c ++ 0x的基于范围的循环.但是,g ++(版本4.6.3)告诉我,begin或者没有匹配的函数end.

我的代码:

#include <iostream>
#include <cinttypes>

class bitscan {
    uint64_t mask;
public:
    bitscan(uint64_t m) : mask(m) {}
    bool operator!=(bitscan it) const {return mask!=it.mask;}
    bitscan &operator++() {mask&=(mask-1);return *this;}
    int operator*() {return __builtin_ctzl(mask);}
};

bitscan begin(uint64_t m) {return m;}
bitscan end(uint64_t m) {return 0;}

int main() {
    uint64_t num=49;
    for (int i : num) std::cout<<i<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

错误:

err.cpp: In function ‘int main()’:
err.cpp:18:15: error: no matching function for call to ‘begin(long unsigned int&)’
err.cpp:18:15: note: …
Run Code Online (Sandbox Code Playgroud)

c++ for-loop g++ c++11 bitboard

2
推荐指数
1
解决办法
732
查看次数

为C代码创建makefile,无需运行./

我需要创建一个makefile,将编译我simpleprogram.csp和它可以被称为像Unix命令一样ls,ps等等,没有明确地写./sp.我查看了网络,无法找到解决方案,或以错误的方式搜索它.我不能搜索"没有./的可执行文件",因为我不知道这是什么叫=>" ./"

c unix makefile

0
推荐指数
1
解决办法
220
查看次数

标签 统计

c++ ×3

c ×2

c++11 ×2

bitboard ×1

exception ×1

for-loop ×1

g++ ×1

makefile ×1

move-semantics ×1

unix ×1