![](/img/trans.png)
[英]Visual Studio debugger fails but program runs fine when built…?
[英]Program with bound method is built but fails to launch
考慮使用 gcc 在 C++11 下編譯的以下代碼:
#include <cstdio>
#include <functional>
#include <unordered_map>
using namespace std;
using namespace std::placeholders;
class Box
{
char* box;
public:
Box(): box(new char[128]) {}
~Box()
{
delete[] this->box;
}
void example(int a, int b)
{
printf("%d %d", a, b);
}
};
Box box;
unordered_map<char, function<void(int, int)>> methods = {
{'a', bind(&Box::example, box, _1, 8)}
};
int main()
{
fputs("Main called.", stdout);
return 0;
}
該程序可以無錯誤地構建,但嘗試啟動它會被忽略或導致失敗。
在 Windows 10 上,通過命令提示符啟動生成的 exe 文件只會打印一個沒有解釋的空行,即使程序應該輸出Main called.
.
在 VS Code 的集成終端中運行它時,我得到了更好的錯誤消息:
The terminal process "C:\WINDOWS\System32\cmd.exe /d /c {path to exe file} failed to launch (exit code: 3221226356).
當我將 Box 定義更改為不使用 box 成員的指針時,它可以工作:
class Box
{
char box[128];
public:
void example(int a, int b)
{
printf("%d %d", a, b);
}
};
是什么賦予了?
這是 C++ 幾個神秘方面的組合:
unordered_map<char, function<void(int, int)>> methods = {
{'a', bind(&Box::example, box, _1, 8)}
};
如果您將其更改為:
unordered_map<char, function<void(int, int)>> methods = {
{'a', bind(&Box::example, &box, _1, 8)}
};
代碼應該仍然可以編譯,並且運行時不會出錯。 使用 gcc 10 驗證。
你的類Box
違反了三規則。 如果Box
對象被復制構造,則會有具有相同指針的單個Box
對象的副本,並且當它們都被銷毀時,將多次嘗試delete
相同的指針。 希拉里隨之而來。
所以這是引起您問題的第一個因素:您的課程不符合規則 3。
第二個問題是std::bind
非常通用並且有多個重載。 您在程序中使用的重載有效地歸結為(作為其內部工作的一部分)生成了box
對象的內部副本,從而觸發了規則 3 違規。
但是std::bind
也可以在這里使用指向具有綁定方法的對象的指針,這避免了復制它的需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.