智能指针是下面的指针,那么有没有办法将shared_ptr
函数的参数定义为不别名 anothershared_ptr
或任何类型的另一个指针?
还是出于某种原因,这是不必要的?
我关心 gcc >=4.2 和 llvm-clang >=2.0 编译器(其他编译器的答案也很有趣)。
智能指针是下面的指针,那么有没有办法将shared_ptr
函数的参数定义为不别名 anothershared_ptr
或任何类型的另一个指针?
还是出于某种原因,这是不必要的?
我关心 gcc >=4.2 和 llvm-clang >=2.0 编译器(其他编译器的答案也很有趣)。
只需提取指针.get()
并将它们标记为__restrict__
. 请记住,放入__restrict__
函数参数与放入__restrict__
局部变量相同。特别是,编译器不会试图阻止您使用两个明显指向同一个对象的指针来调用函数。例如foo(i,i)
。
如果您想向编译器承诺某些指针不会相互引用,从而允许编译器进行更多优化,请使用下面的代码并通过xp
andyp
而不是x
and进行操作y
。
#include<iostream>
#include<memory>
using namespace std;
void foo(shared_ptr<int> x, shared_ptr<int> y) {
int * __restrict__ xp = x.get();
int * __restrict__ yp = y.get();
}
int main() {
shared_ptr<int> i = make_shared<int>(3);
shared_ptr<int> j = make_sharet<int>(4);
foo(i,j);
}
如果要对与共享指针关联的底层对象执行非别名操作,可以显式委托给采用非别名指针参数的工作例程:
void worker (mytype *__restrict x, mytype *__restrict y)
{
// do something with x, y with a no-alias guarantee
}
int main()
{
std::shared_ptr<mytype> p(new mytype);
std::shared_ptr<mytype> q(new mytype);
// explicitly delegate the shared object
worker(p.get(), q.get());
return 0;
}
我不确定您到底在想什么,但这将允许智能指针安全地处理高级内存管理,同时使用无别名指针可能更有效地执行低级工作。
正如@BenVoigt 指出的那样,restrict
它只是正式的一部分c99
-c++
不应该对此一无所知。MSVC
无论如何都支持它__restrict
,正如你所说GCC
的那样__restrict__
。
希望这可以帮助。