在我的代码中,我使用了来自Scott Meyers Effective Modern C++的Item 32建议,在那里他解释了如何在C++ 11中进入捕获.示例代码运行良好.
class Some
{
public:
void foo()
{
std::string s = "String";
std::function<void()> lambda = std::bind([this](std::string& s) {
bar(std::move(s));
}, std::move(s));
call(std::move(lambda));
}
void bar(std::string)
{
// Some code
}
void call(std::function<void()> func)
{
func();
}
};
int main()
{
Some().foo();
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用参数中更难以捕获的方式移动,但它不起作用,存在一些编译错误.请帮我修理一下.代码有错误如下.我玩过它,但找不到解决方案.有可能吗?
class Some
{
public:
void foo()
{
std::string stringToMove = "String";
std::function<void(std::string, int, int)> lambda =
std::bind([this](std::string s, int i1, int i2, std::string& stringToMove) {
bar(std::move(stringToMove), i1, i2);
}, std::move(stringToMove));
call(std::move(lambda)); …Run Code Online (Sandbox Code Playgroud) 我想让我的应用程序多线程.当我添加2个独立的独立线程时,我收到了运行时错误消息.我找不到解决方案.也许有人可能会帮忙.
这是运行时错误图像的链接https://postimg.org/image/aasqn2y7b/
threads.h
#include <thread>
#include <atomic>
#include <chrono>
#include <iostream>
class Threads
{
public:
Threads() : m_threadOne(), m_threadTwo(), m_stopper(false) { }
~Threads() {
m_stopper.exchange(true);
if (m_threadOne.joinable()) m_threadOne.join();
if (m_threadTwo.joinable()) m_threadTwo.join();
}
void startThreadOne() {
m_threadOne = std::thread([this]() {
while (true) {
if (m_stopper.load()) break;
std::cout << "Thread 1" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
}
void startThreadTwo() {
m_threadOne = std::thread([this]() {
while (true) {
if (m_stopper.load()) break;
std::cout << "Thread 2" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
}
private: …Run Code Online (Sandbox Code Playgroud) 我虽然在函数调用之后发送到函数的所有rvalue参数都将被销毁.我完全搞砸了这个例子.有人可以帮我吗?也许它解释了一些链接.
class Test
{
public:
Test(const char* name)
: ptr(nullptr)
{
ptr = name;
}
~Test()
{
printf("%s\n", ptr);
system("PAUSE");
}
const char* ptr;
};
int main()
{
Test t("Hello");
}
Run Code Online (Sandbox Code Playgroud) 如何找出函数中传递的参数是字符串还是字符(不确定如何正确调用)文字?
我的功能(不正确):
void check(const char* str)
{
// some code here
}
Run Code Online (Sandbox Code Playgroud)
我想用它来称呼它:
int main()
{
check("Hello"); // Correct call
std::string hello = "Hello";
check(hello.c_str()); // Must be compile error here
}
Run Code Online (Sandbox Code Playgroud)