我有一个的集合unique_ptr。在这里,我想将其中一些带回给呼叫者。调用者只需要阅读内容,所以我想使用常量引用。但是我不确定如何使用unique_ptrs。
这是一些我使用原始指针执行的代码:
class entry
{
};
vector<entry*> master;
const vector<entry*> get_entries()
{
vector<entry*> entries;
// peusocode, master contains all entries.
// only some entries are copied, filtered by some predicate
copy_if(master.begin(), master.end(), back_inserter(entries), ...);
}
Run Code Online (Sandbox Code Playgroud)
我该如何使用unique_ptrs?我也可以使用shared_ptr,但是所有权非常明确,正如我提到的,调用方不需要写访问权。
我有一个带有指向某物的指针的结构。我期望通过指向 const 结构的指针访问该指针会给我一个指向 const 的指针。但在这种情况下 gcc 不会产生警告:
#include <stdlib.h>
struct S {
void* ptr;
};
struct S* create(void)
{
struct S* S = malloc(sizeof(*S));
S->ptr = malloc(sizeof(int));
return S;
}
void some_func(void* p);
int main(void)
{
struct S* S = create();
const void* ptr = S->ptr;
const struct S* SC = S;
some_func(ptr); // warning as expected
some_func(SC->ptr); // no warning
}
Run Code Online (Sandbox Code Playgroud)
那么实际上是SC->ptr一个const void*?我一直以为但现在我很困惑。在这种情况下有可能收到警告吗?