-3 unique-ptr flawed-concept c++11 c++14
我刚刚在一个情况下稳定了一个unique_pointer引用作为函数参数传递.所以我看一下它,发现代码实际上是在编译和运行.
为什么会这样?当你可以引用那个指针时,指针是如何唯一的?
这是我的例子:
class Foo{
public:
int bar{23};
};
void Bar(std::unique_ptr<Foo>& a_foo){
a_foo->bar = 42;
}
int main(int argc, char *argv[]){
auto foo{ std::make_unique<Foo>() };
Bar(foo);
std::cout << foo->bar << std::endl; //outputs 42
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当你可以引用那个指针时,指针是如何唯一的?
您可以根据需要为该指针提供尽可能多的引用,但实际上只有一个引用.
删除,&
以便您尝试复制unique_ptr
,并且您的程序将无法构建.您不能克隆/复制指针,以便有多个指向同一个东西.这就是"独特"的含义.
归档时间: |
|
查看次数: |
111 次 |
最近记录: |