我正在考虑使用"自杀对象"来模拟游戏中的实体,即能够自行删除的对象.现在,一般的C++ 03的实现(普通旧delete this)不执行任何潜在指的自杀的对象,这就是为什么我使用的其他对象std::shared_ptr和std::weak_ptr.
现在进行代码转储:
#include <memory>
#include <iostream>
#include <cassert>
struct SuObj {
SuObj() { std::cout << __func__ << '\n'; }
~SuObj() { std::cout << __func__ << '\n'; }
void die() {
ptr.reset();
}
static std::weak_ptr<SuObj> create() {
std::shared_ptr<SuObj> obj = std::make_shared<SuObj>();
return (obj->ptr = std::move(obj));
}
private:
std::shared_ptr<SuObj> ptr;
};
int main() {
std::weak_ptr<SuObj> obj = SuObj::create();
assert(!obj.expired());
std::cout << "Still alive\n";
obj.lock()->die();
assert(obj.expired());
std::cout << "Deleted\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此代码似乎工作正常.但是,我想让别人去关注它.这段代码有意义吗?我是否盲目地驶入未定义的土地?我应该放弃键盘并立即开始艺术研究吗?
我希望这个问题能够充分缩小.看起来有点微小而且低级别的CR. …
在下面的代码中,如何返回引用floor而不是新对象?是否可以让函数返回借用的引用或拥有的值?
extern crate num; // 0.2.0
use num::bigint::BigInt;
fn cal(a: BigInt, b: BigInt, floor: &BigInt) -> BigInt {
let c: BigInt = a - b;
if c.ge(floor) {
c
} else {
floor.clone()
}
}
Run Code Online (Sandbox Code Playgroud) fn main() {
let mut name = String::from("Charlie");
let x = &mut name;
let y = x; // x has been moved
say_hello(y);
say_hello(y); // but y has not been moved, it is still usable
change_string(y);
change_string(y);
}
fn say_hello(s: &str) {
println!("Hello {}", s);
}
fn change_string(s: &mut String) {
s.push_str(" Brown");
}
Run Code Online (Sandbox Code Playgroud)
当我分配x到y x已被移动。但是,当我在函数中使用它时,我希望可以移动具有移动语义的东西。但是,我仍然可以在后续调用后使用参考。也许这与 say_hello() 接受不可变引用有关,但 change_string() 接受可变引用但引用仍未移动。
需要阻止root更新git(工作)目录.推理包括但不限于:防止不合适的文件系统所有权更改.
没有任何git钩子在它发生之前似乎阻止了一个fetch/merge/pull,类似于pre-commit hook.或者至少,我在这里(或在手册页中)看不到任何内容:http: //www.analysisandsolutions.com/code/git-hooks-summary-cheat-sheet.htm
思考?
我必须迭代键,通过键在 HashMap 中找到值,可能在找到的结构中做一些繁重的计算作为一个值(懒惰 => 改变结构)并在 Rust 中缓存返回它。
我收到以下错误消息:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:25:26
|
23 | fn it(&mut self) -> Option<&Box<Calculation>> {
| - let's call the lifetime of this reference `'1`
24 | for key in vec!["1","2","3"] {
25 | let result = self.find(&key.to_owned());
| ^^^^ `*self` was mutably borrowed here in the previous iteration of the loop
...
28 | return result
| ------ returning this value requires that …Run Code Online (Sandbox Code Playgroud) 为了说明 的必要性Rc<T>,本书提供了以下代码片段(剧透:它不会编译)来表明,如果没有Rc<T>.
enum List {\n Cons(i32, Box<List>),\n Nil,\n}\n\nuse crate::List::{Cons, Nil};\n\nfn main() {\n let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));\n let b = Cons(3, Box::new(a));\n let c = Cons(4, Box::new(a));\n}\nRun Code Online (Sandbox Code Playgroud)\n然后它声称(强调我的)
\n\n\n我们可以更改 的定义来
\nCons保存引用,但随后我们必须指定生命周期参数。通过指定生命周期参数,我们将指定列表中的每个元素的生存时间至少与整个列表一样长。例如,借用检查器不会让我们进行编译,因为在 a 可以引用它之前,临时值将被删除。let a = Cons(10, &Nil);Nil
嗯,不完全是。以下代码片段在下编译rustc 1.52.1
enum List<\'a> {\n Cons(i32, &\'a List<\'a>),\n Nil,\n}\n\nuse crate::List::{Cons, Nil};\n\nfn main() {\n let a = Cons(5, &Cons(10, &Nil));\n let b = Cons(3, …Run Code Online (Sandbox Code Playgroud) 考虑以下示例代码:
#[derive(Clone)]
struct DataRef<'a> {
text: &'a str,
}
#[derive(Clone)]
struct DataOwned {
text: String,
}
Run Code Online (Sandbox Code Playgroud)
我将以这种方式ToOwned实现:DataRef
impl ToOwned for DataRef<'_> {
type Owned = DataOwned;
fn to_owned(&self) -> DataOwned {
DataOwned {
text: self.text.to_owned(),
}
}
}
Run Code Online (Sandbox Code Playgroud)
从字面上看,这句话有道理吧?但也存在一些问题。
第一个问题是,因为ToOwned提供了一个全面的实现:
impl<T> ToOwned for T where T: Clone { ... }
Run Code Online (Sandbox Code Playgroud)
上面的代码会出现编译错误:
error[E0119]: conflicting implementations of trait `std::borrow::ToOwned` for type `DataRef<'_>`
--> src/main.rs:13:1
|
13 | impl ToOwned for DataRef<'_> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| …Run Code Online (Sandbox Code Playgroud) 我正在努力克服以下情况.
给定存储在NTFS卷上的目录,其中:
(或者简而言之,所有管理员都被锁定在文件夹之外)
但!
(或者简而言之,我有权修复DACL /所有者)
我对以下代码应该没有问题:
WindowsIdentity privilegedUser = System.Security.Principal.WindowsIdentity.GetCurrent();
// I cannot use File.GetAccessControl() as I get access denied
// (working as intended! I have no access to read the ACL!)
// so I have to write a new ACL:
FileSecurity acl = new FileSecurity();
acl.SetOwner(admin.User);
acl.AddAccessRule(new FileSystemAccessRule(privilegedUser.User, FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl("c:\\path\\to\\broken", acl);
Run Code Online (Sandbox Code Playgroud)
但是,SetAccessControl调用会抛出UnauthorizedAccessException.当我改变它只调整所有者时,同样的事情发生.当我只尝试调整DACL时,同样的事情.
我通过在Process Explorer中检查生成的进程并验证Administrators组是否设置为"Owner"而不是"Disabled"来验证问题不是UAC.我应该拥有执行此操作所需的所有权限(备份操作员在面对管理员时应该是无关紧要的,但我将其添加进行测试) - 但它只是继续拒绝访问权限.
相关的technet文档:http://technet.microsoft.com/en-us/library/cc783530%28WS.10%29.aspx
以下代码有效,但不确定它是否正确.几个问题:
Path或PathBuf?AsRef吗?PathBuf::from(path)为了拥有结构所拥有的路径吗?use std::fmt;
use std::path::PathBuf;
struct Example {
path: PathBuf,
}
impl fmt::Display for Example {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.path.to_str().unwrap())
}
}
impl Example {
fn new(path: &PathBuf) -> Example {
// Do something here with path.
Example {
path: PathBuf::from(path),
}
}
}
fn main() {
let x = Example::new(&PathBuf::from("test.png"));
println!("{}", x);
}
Run Code Online (Sandbox Code Playgroud)
一些上下文:我试图对应该知道自己路径的文件进行高级抽象.也许设计是完全错误的.
根据The Rust 的书:
Rust 中的每个值都有一个变量,称为其所有者。一次只能有一个所有者。当所有者超出范围时,该值将被删除。
静态项目不会在程序结束时调用 drop。
在阅读了这篇 SO post并给出了下面的代码后,我明白这foo是一个值,其变量y相当于&y因为“字符串文字是字符串切片”,被称为它的owner. 那是对的吗?还是静态项目没有所有者?
let x = String::from("foo"); // heap allocated, mutable, owned
let y = "foo" // statically allocated to rust executable, immutable
Run Code Online (Sandbox Code Playgroud)
我想知道,因为与拥有的不同String,字符串文字没有移动,大概是因为它们存储在.rodata可执行文件中。
fn main() {
let s1 = "foo"; // as opposed to String::from("foo")
let s2 = s1; // not moved
let s3 = s2; // no …Run Code Online (Sandbox Code Playgroud) ownership ×10
rust ×7
reference ×2
c# ×1
c++ ×1
git ×1
git-pull ×1
githooks ×1
immutability ×1
ntfs ×1
path ×1
permissions ×1
shared-ptr ×1
string ×1