简体   繁体   English

c ++使用指针时的移动语义

[英]c++ move semantics when using pointers

How do I use the move assignment operator when working with raw pointers.使用原始指针时如何使用move赋值运算符。

Is there any other way than doing something like:除了做这样的事情还有其他方法吗:

void Function(T* dest)
{
    T* src = LoadT();
    (*dest) = std::move(*src);
    delete src;
}

Your move is fine.你的举动没问题。 The object pointed to by src will be moved into the object pointed to by dest. src 所指向的对象将被移动到 dest 所指向的对象中。

About your updated code example, the version with Function:关于您更新的代码示例,具有 Function 的版本:

If your LoadT() returns a raw pointer to an object allocated with new, that does not get stored somewhere else and later deleted, you will have a memory leak.如果您的 LoadT() 返回一个指向使用 new 分配的对象的原始指针,该对象不会存储在其他地方并随后被删除,则会出现内存泄漏。

When you std::move something, you move the contents of that object, the object itself remains alive, only "empty"/in whatever state you leave it after moving.当您 std::move 某物时,您移动该对象的内容,该对象本身保持活动状态,只有“空”/在移动后离开它的任何状态。

If you return a pointer to an object that is owned by someone else and will be cleaned up somehow beyond the code that's seen here, you could make that explicit by changing your pointers to references - that way you will explicitly specify that: a) the pointers are guaranteed to not be null;如果您返回一个指向其他人拥有的对象的指针,并且将在此处看到的代码之外以某种方式进行清理,您可以通过更改指向引用的指针来明确说明 - 这样您将明确指定:a)指针保证不为空; b) that there should be no worries about deleting the object you get from LoadT, since a reference can't have ownership of that object. b) 不必担心删除从 LoadT 获得的对象,因为引用不能拥有该对象的所有权。

Unless you reference the objects in a temporary variable you are out of luck.除非您在临时变量中引用对象,否则您就不走运了。 Technically (not sure if illegal) you are allowed to provide your own specialization of move in which you can hide that behavior.从技术上讲(不确定是否非法),您可以提供自己的move ,您可以在其中隐藏该行为。 But at one point or another, you have to dereference those pointers.但是在某一时刻,您必须取消引用这些指针。

You want to have the pointed-to-object s moved onto one another, then you are already doing that in the correct/standard/only way, that is de-reference the pointer and then move *src onto *dest .您想让指向的对象相互移动,那么您已经以正确/标准/唯一的方式这样做了,即取消引用指针,然后*src移动*dest


That being said, you interface is semanticly 'problematic' .话虽如此,您的界面在语义上是“有问题的” A pointer to a function is by convention taken to mean non-owning and optional.按照惯例,指向函数的指针意味着非拥有和可选。 Ownership seems not to be the issue here, but optional is.所有权似乎不是这里的问题,但可选的是。 Why use a pointer when you can use a reference ?当您可以使用引用时,为什么要使用指针? and moreover why use a reference when you can just use return value ?此外,当您可以只使用返回值时,为什么还要使用引用?

In effect you could simplify to:实际上,您可以简化为:

T Function()
{
    return LoadT();
}

Then let users of the function decide how to best use T. If T is polymorphic you could return std::unique_ptr<T> instead.然后让函数的用户决定如何最好地使用 T。如果 T 是多态的,你可以返回std::unique_ptr<T>代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM