9

智能指针是下面的指针,那么有没有办法将shared_ptr函数的参数定义为不别名 anothershared_ptr或任何类型的另一个指针?

还是出于某种原因,这是不必要的?

我关心 gcc >=4.2 和 llvm-clang >=2.0 编译器(其他编译器的答案也很有趣)。

4

2 回答 2

8

只需提取指针.get()并将它们标记为__restrict__. 请记住,放入__restrict__函数参数与放入__restrict__局部变量相同。特别是,编译器不会试图阻止您使用两个明显指向同一个对象的指针来调用函数。例如foo(i,i)

如果您想向编译器承诺某些指针不会相互引用,从而允许编译器进行更多优化,请使用下面的代码并通过xpandyp而不是xand进行操作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);
}
于 2012-01-29T00:53:23.483 回答
5

如果要对与共享指针关联的底层对象执行非别名操作,可以显式委托给采用非别名指针参数的工作例程:

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__

希望这可以帮助。

于 2012-01-29T00:52:33.263 回答