将C ++对象移动到内存位置

时间:2015-07-24 13:42:13

标签: c++ c++11 move-semantics

我可能需要做类似于std :: vector的操作:

T *mem = malloc(...); // notice this is just memory allocation.
T t;
move... t to mem
mem->doSomething();

如何将t移到已分配的内存上?

如何将对象从已分配的内存移动到新变量。

如何从已分配的内存中删除对象 - 手动调用d-tor?

我必须使用展示新的和赋值运算符吗?

2 个答案:

答案 0 :(得分:1)

就像这样,但如果你不知道自己在做什么,那么我会避免这样做:

#include <new>
#include <stdlib.h>

void* mem = malloc(sizeof(T));
T t;
T* tt = new(mem) T( std::move(t) );
tt->doSomething();
tt->~T();
free(mem);

你无法按字面意思移动&#34; t到那个记忆,t将永远是它的创建地点,但你可以在那个位置创建另一个对象,作为t的副本(使用移动构造函数来制作副本)如果它有一个,但仍然留下t它仍然存在的地方。

答案 1 :(得分:1)

您无法移动实时对象,但您可以从中移动构建另一个对象。

int main() {
    std::string str = "Hello World !";

    // Allocate some storage
    void *storage = std::malloc(sizeof str);

    std::cout << str << '\n';

    // Move-contruct the new string inside the storage
    std::string *str2 = new (storage) std::string(std::move(str));

    std::cout << str << '|' << *str2 << '\n';

    // Destruct the string and free the memory
    str2->~basic_string();
    free(storage);
}

输出:

Hello World !
|Hello World !