小编hao*_*ang的帖子

是否保证在返回时移动对象?

我知道当按值将对象传递给函数时,如果存在构造函数,则始终调用移动构造函数,假设没有复制省略.如何按值返回对象?

例如,假设我们有一个Foo具有移动构造函数的类,并且我们有一个返回Foo对象的函数.

Foo g() {
    Foo f;

    // do something with f

    return f;
}
Run Code Online (Sandbox Code Playgroud)

如果我们假设没有RVO,那么移动构造函数是否可以保证被调用?

更新:我想我没有明确表达我的意图.我只是想知道我可以在最坏的情况下移动对象而不是复制.无论是RVO还是NRVO,我很高兴.我还应该说移动构造函数和移动赋值不会被删除并且正确实现.

c++ return-value move-semantics c++11

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

对std :: hash <string>的未定义引用

我正在尝试编写一个简单的工厂函数std::unordered_map.该函数接受一个iterable,它有一个beginend方法,并且value_type是a std::pair.以下是我提出的代码.

#include <string>
#include <unordered_map>
#include <cassert>
#include <algorithm>

template <class Iterable>
std::unordered_map<typename Iterable::value_type::first_type,
    typename Iterable::value_type::second_type>
make_unordered_map(Iterable const &iter)
{
    return std::unordered_map<typename Iterable::value_type::first_type,
        typename Iterable::value_type::second_type>(
        iter.begin(), iter.end());
}

int main()
{
    std::unordered_map<std::string, int> map =
        {{"a", 0}, {"b", 1}, {"c", 2}};
    auto result = make_unordered_map(map);
    assert(std::equal(result.begin(), result.end(), map.begin()));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,我得到一个很长的链接器错误列表,它基本上要求std::hash专门的类std::string.

undefined reference to `std::hash<std::basic_string<char, std::char_traits<char>,
std::allocator<char> > const>::operator()(std::basic_string<char,
std::char_traits<char>, std::allocator<char> >) const'
Run Code Online (Sandbox Code Playgroud)

我正在使用GCC 4.6.1,有 …

c++ c++11

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

标签 统计

c++ ×2

c++11 ×2

move-semantics ×1

return-value ×1