在QThread 类的文档中,一个示例设置的工作方式如下:
public:
Controller() {
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
//some connects to thread and worker
workerThread.start();
}
~Controller() {
workerThread.quit();
workerThread.wait();
}
Run Code Online (Sandbox Code Playgroud)
Qt 是否使用moveToThread(...)此处的函数实现了实际的移动语义?即线程是否会在完成后重新分配 Worker 对象,因为分配的对象永远不会Worker*在Controller()任何地方显式删除?
fn func(s: *mut String, a: *mut i32) -> usize {
println!("{}", unsafe { *s });
println!("{}", unsafe { *a });
unsafe { (*s).len() }
}
fn main() {
let mut s = String::from("hello");
let mut a = 10;
func(&mut s, &mut a);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码失败并出现错误:
fn func(s: *mut String, a: *mut i32) -> usize {
println!("{}", unsafe { *s });
println!("{}", unsafe { *a });
unsafe { (*s).len() }
}
fn main() {
let mut s = String::from("hello");
let mut a …Run Code Online (Sandbox Code Playgroud) Considering only objects that are movable but non-copyable (e.g., std::thread or std::unique_ptr), I want to transfer the ownership of the resource such an object contains by passing it as an argument to a constructor. I'm comparing two approaches: the constructor taking the object by value vs. by rvalue reference.
As an example with std::thread, consider the following class Value whose constructor takes an std::thread by value:
#include <thread>
#include <utility>
struct Value {
Value(std::thread th): th_(std::move(th)) …Run Code Online (Sandbox Code Playgroud) c++ ownership-semantics parameter-passing move-semantics c++11
我遇到了类似于以下(或多或少最小)示例的 C++ 代码。请考虑底部函数中标记的方法调用:
#include <memory>
static unsigned returnValue = 5;
void setReturnValue(unsigned u) { returnValue = u; }
class MyObject
{
public:
MyObject(unsigned uIN) : u(uIN) {}
~MyObject() { u = 42; }
void method(std::unique_ptr<MyObject> uniqPtrToObject)
{
// Do something fancy with this unique pointer now,
// which will consume the object and its data
setReturnValue(uniqPtrToObject->getValue());
}
unsigned getValue() { return u; }
private:
unsigned u; // Some relevant object data
};
std::unique_ptr<MyObject> GetUniqToObject(unsigned u)
{
// Get the object …Run Code Online (Sandbox Code Playgroud) 例如,
class Test{
private:
int* foo;
public:
Test(int* foo){this->foo = foo;}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,有什么办法可以在析构函数中删除 foo 吗?我是否必须在析构函数中删除 foo 或者至少将其设置为 nullptr?