我对这个程序有一些疑问:
#include <iostream>
#include <type_traits>
#include <functional>
using namespace std;
template <typename T> void foo ( T x )
{
auto r=ref(x);
cout<<boolalpha;
cout<<is_same<T&,decltype(r)>::value;
}
int main()
{
int x=5;
foo (x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
false
Run Code Online (Sandbox Code Playgroud)
我想知道,如果std::ref没有返回对象的引用,那么它会做什么?基本上,有什么区别:
T x;
auto r = ref(x);
Run Code Online (Sandbox Code Playgroud)
和
T x;
T &y = x;
Run Code Online (Sandbox Code Playgroud)
另外,我想知道为什么存在这种差异?为什么我们需要std::ref或std::reference_wrapper什么时候有参考(即T&)?
我有一个class A我希望有一个指向函数的指针作为数据成员:
class A
{
protected:
double (*ptrToFunction) ( double );
public:
...
//Setting function according to its name
void SetPtrToFunction( std::string fName );
};
Run Code Online (Sandbox Code Playgroud)
但是,如果我想ptrToFunction有时候double,有时甚至int是这样的话:
//T is a typename
T(*ptrToFunction) ( double );
Run Code Online (Sandbox Code Playgroud)
在这种情况下我该如何申报呢?
我正在尝试使用以下代码片段将对矢量转换&str为a HashMap:
use std::collections::HashMap;
fn main() {
let pairs = vec!(("foo", "bar"), ("toto", "tata"));
let map: HashMap<&str, &str> = pairs.iter().collect();
println!("{:?}", map);
}
Run Code Online (Sandbox Code Playgroud)
但是编译失败并出现此错误:
<anon>:5:47: 5:56 error: the trait `core::iter::FromIterator<&(&str, &str)>` is not implemented for the type `std::collections::hash::map::HashMap<&str, &str>` [E0277]
<anon>:5 let map: HashMap<&str, &str> = pairs.iter().collect();
Run Code Online (Sandbox Code Playgroud)
但是,如果我.cloned()在调用之前添加collect()一切正常:
...
let map: HashMap<&str, &str> = pairs.iter().cloned().collect();
...
Run Code Online (Sandbox Code Playgroud)
即使我理解错误消息(没有FromIterator<&(&str, &str)>该类型的特征的实现HashMap<&str, &str>)我不明白类型&(&str, &str)来自哪里(根据Rust文档中的方法签名)以及为什么调用cloned()修复这个问题.
我正在寻找一种学习语言,我看到Rust变得非常受欢迎.
关于Rust,内存安全和防止段错的两件事让我印象深刻.
Rust如何实现这一目标?例如,Rust和Java之间有什么区别可以实现Rust的安全功能?
以下C++ 11代码是我认为在clang中触发误报的最小示例:
#include <iostream>
#include <list>
#include <memory>
class ElementType {};
int main(int argc, const char * argv[]) {
std::list<std::unique_ptr<ElementType>> theList(5);
theList.pop_front();
for (const auto &element: theList) { // (*)
std::cout << "This should be fine." << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在由星号(*)标记的线上,铿锵声分析仪声称
... filePath ... /main.cpp:21:29:释放后使用内存(在调用'begin'时)
据我解释,这段代码是无害的,但是clang忽略了这样的观点:std::list<T>::pop_front()不仅要调用它的元素的析构函数,还要调整它的位置std::list<T>::begin().更换呼叫pop_front通过pop_back使得该分析仪警告消失,甚至被替换它erase(theList.begin())使它走出无警告.
我是否遗漏了某些东西或者我是否真的偶然发现了一个错过的铿锵声?
供参考:这些结果来自Mac OS X 10.9.2上的XCode 5.1.1(5B1008),
$ clang --version
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.1.0
Thread model: …Run Code Online (Sandbox Code Playgroud) 我在尝试一系列不同的技术时提出了我的问题,但我没有多少经验.可悲的是,我甚至不知道我是否犯了一个愚蠢的逻辑错误,我是否使用了glium箱子错误,我是否搞砸了GLSL等等.无论如何,我设法从头开始一个新的Rust项目,努力寻找一个显示我的问题的最小例子,问题至少在我的电脑上重现.
最小的例子最终难以解释,所以我首先做一个更小的例子来做我想做的事情,虽然通过黑客攻击并限制为128个元素(4倍32位,在a中GLSL uvec4) .从这一点来看,我的问题出现的版本的步骤非常简单.
uniform和位移程序在屏幕上创建一个矩形,纹理坐标从水平0.0到128.0水平.该程序包含一个用于矩形的顶点着色器,以及一个片段着色器,它使用纹理坐标在矩形上绘制垂直条纹:如果纹理坐标(夹到a uint)是奇数,则在纹理坐标为偶数时绘制一种颜色,它绘制另一种颜色.
// GLIUM, the crate I'll use to do "everything OpenGL"
#[macro_use]
extern crate glium;
// A simple struct to hold the vertices with their texture-coordinates.
// Nothing deviating much from the tutorials/crate-documentation.
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
tex_coords: [f32; 2],
}
implement_vertex!(Vertex, position, tex_coords);
// The vertex shader's source. Does nothing special, except passing the …Run Code Online (Sandbox Code Playgroud) 我有以下Rust程序,它将一个闭包传递给一个生命周期中的泛型函数'a和一个类型的闭包F,它通过引用一些本地数据来调用闭包:
fn other_function<'a, F>(f: F)
where F: Fn(&'a u32)
{
let the_value = 0;
f(&the_value);
}
fn main() {
other_function(|_| { /* do nothing */ });
}
Run Code Online (Sandbox Code Playgroud)
这无法编译,并显示以下消息:
<anon>:5:8: 5:17 error: `the_value` does not live long enough
<anon>:5 f(&the_value);
^~~~~~~~~
<anon>:3:1: 6:2 note: reference must be valid for the lifetime 'a as defined on the block at 3:0...
<anon>:3 {
<anon>:4 let the_value = 0;
<anon>:5 f(&the_value);
<anon>:6 }
<anon>:4:23: 6:2 note: ...but borrowed value is …Run Code Online (Sandbox Code Playgroud) 我遇到多个线程必须更新存储在共享向量中的对象的情况。但是,向量非常大,并且要更新的元素数量相对较少。
在最小示例中,可以通过包含要更新的元素的索引的(哈希)集来标识要更新的元素集。因此,代码如下所示:
let mut big_vector_of_elements = generate_data_vector();
while has_things_to_do() {
let indices_to_update = compute_indices();
indices_to_update.par_iter() // Rayon parallel iteration
.map(|index| big_vector_of_elements[index].mutate())
.collect()?;
}
Run Code Online (Sandbox Code Playgroud)
Rust显然不允许这样做:big_vector_of_elements不能同时在多个线程中可变地借用。但是,将每个元素包装在例如Mutex锁中似乎是不必要的:如果没有明确的同步,这种特定情况将是安全的。由于索引来自一组,因此可以保证它们是不同的。par_iter在向量的相同元素上没有两次迭代。
编写一个并行修改向量中元素的程序的最佳方法是什么,在这种情况下,同步已经通过选择索引来解决,但是编译器不理解后者呢?
接近最佳的解决方案是将所有元素包装big_vector_of_elements在某种假设的UncontendedMutex锁中,这是其变体,Mutex在无竞争的情况下非常快,并且在发生争用(甚至发生恐慌)时可能会花费任意长时间。理想情况下,an UncontendedMutex<T>的大小和对齐方式也应与Tany相同T。
可以使用“使用人造丝的并行迭代器”,“使用chunks_mut”或“使用split_at_mut” 来回答多个问题:
这些答案在这里似乎无关紧要,因为这些解决方案意味着迭代整个big_vector_of_elements,然后针对每个元素弄清楚是否需要更改任何内容。从本质上讲,这意味着这样的解决方案如下所示:
let mut big_vector_of_elements = generate_data_vector();
while has_things_to_do() {
let indices_to_update = compute_indices();
for (index, mut element) in big_vector_of_elements.par_iter().enumerate() …Run Code Online (Sandbox Code Playgroud) 我有两个测试应用程序:App1和App2.
App1从文本字段中获取String并触发方法:
@IBAction func openApp(sender: AnyObject) {
let url1 = ("app2://com.application.started?displayText="+textToSend.text!)
let url2 = url1.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
UIApplication.sharedApplication().openURL(NSURL(string: url2!)!)
}
Run Code Online (Sandbox Code Playgroud)
这实际上打开了App2,其中只有标签应该更改为通过url发送的文本,代码在AppDelegate.swift中:
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
let url = url.standardizedURL
let query = url?.query
ViewController().labelToDisplayResult.text = query
return true;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我试图将URL的结果传递给实际标签的行给了我这个错误:
EXC_BAD_INSTRUCTION (CODE=EXC_I386_INVOP SUBCODE=0x0)
Run Code Online (Sandbox Code Playgroud)
但是我确实在App2中有所有数据,因为我可以在调试器中看到它们的值:
url NSURL "app2://com.application.started?displayText=564315712437124375" 0x00007fa4e3426320
query String? "displayText=564315712437124375"
Run Code Online (Sandbox Code Playgroud)
知道我为什么会收到这个错误吗?
谢谢...