相关疑难解决方法(0)

std::move 如何使原始变量的值无效?

在cpp 参考中的以下示例中:

#include <iostream>
#include <utility>
#include <vector>
#include <string>

int main()
{
    std::string str = "Hello";
    std::vector<std::string> v;

    // uses the push_back(const T&) overload, which means 
    // we'll incur the cost of copying str
    v.push_back(str);
    std::cout << "After copy, str is \"" << str << "\"\n";

    // uses the rvalue reference push_back(T&&) overload, 
    // which means no strings will be copied; instead, the
    // Contents of str will be moved into the vector.  This is
    // less …
Run Code Online (Sandbox Code Playgroud)

c++ move move-semantics c++11 stdmove

2
推荐指数
2
解决办法
1726
查看次数

C++ std::move 一个指针

我有一个 C++ 框架,我提供给我的用户,他们应该使用我用自己的实现编写的模板化包装器作为模板化类型。包装器充当 RAII 类,它持有一个指向用户类实现的指针。为了使用户的代码干净整洁(在我看来),我提供了一个强制转换运算符,它将我的包装器转换为它所持有的指针。这样(连同其他一些重载)用户可以使用我的包装器,就好像它是一个指针(很像一个 shared_ptr)。

我遇到了一个极端情况,用户调用一个函数,该函数使用指向他的实现类的指针,在我的包装器上使用 std::move。下面是它的外观示例:

#include <iostream>
using namespace std;

struct my_interface {
    virtual int bar() = 0;
};

template <typename T>
struct my_base : public my_interface {
    int bar() { return 4; }
};

struct my_impl : public my_base<int> {};

template <typename T>
struct my_wrapper {
    my_wrapper(T* t) {
        m_ptr = t;
    }

    operator T*() {
        return m_ptr;
    }

private:
    T* m_ptr;
};

void foo(my_interface* a) {
    std::cout << a->bar() << std::endl;
}


int main()
{ …
Run Code Online (Sandbox Code Playgroud)

c++ templates operator-overloading move-semantics c++11

1
推荐指数
1
解决办法
2万
查看次数

C ++如何将对象移至nullptr

我在想一个奇怪的用例,我想将对象移到nullptr。也许我应该给出一个代码片段:

class Objpair {
   public:
      Objpair(Obj&& a, Obj&&b) : first(&a), second(&b) { }
   private:
       Obj* first;
       Obj* second;
};
Run Code Online (Sandbox Code Playgroud)

问题在于,当a和b超出范围时,第一和第二指针将悬空。如果我可以将Object a移到第一个指针上,那么应该就不会出现双重释放和作用域问题。如果首先将成员声明为Obj而不是Obj *指针,则直接的first(std :: move(a))将完成此工作。我在这里一定做错了。我正在考虑移动而不是复制,因为我试图将控制权从另一个对象转移到当前对象并提高性能。

使用指针版本是因为我正在考虑成员对象的多态行为。

c++ pointers move c++11

1
推荐指数
1
解决办法
105
查看次数