【问题标题】:How is std::auto_ptr initialized with a rvalue?std::auto_ptr 如何用右值初始化?
【发布时间】:2016-06-17 15:37:53
【问题描述】:
#include <iostream>
#include <string>
#include <memory>
#include <cstdlib>

std::string foo()
{
    return std::string("yyyyyyyyyyyyy");
}

void bar(std::string& s)
{
    std::cout << s << std::endl;
}


std::auto_ptr<std::string> foo1()
{
    bool x = std::rand() % 2;
    if (x) {
        return std::auto_ptr<std::string>(new std::string("eeeeeeeeeeee"));
    } else {
        return std::auto_ptr<std::string>(new std::string("aaaaaaaaaaaaa"));
    }
}


int main()
{
    //bar(foo());
    std::auto_ptr<std::string> a(foo1());    
}

注释行:bar(foo()) 无法编译,因为 bar 接受非常量引用,foo 返回右值。但是带有std::auto_ptr 的第二行编译。 std::auto_ptr 的复制构造函数也接受非常量引用。为什么它会编译?我在foo1 中使用了std::rand() 来消除RVO(返回值优化)。

【问题讨论】:

  • [FYI] std::auto_ptr 已弃用。它已被std::unique_ptrstd::shared_ptr 取代。
  • 我知道但仍然需要使用旧的编译器。
  • 您可能想要指定 c++98 或 C++03。 C++ 本身包括当前的标准,即 C++14。

标签: c++ copy-constructor c++03 c++98 auto-ptr


【解决方案1】:

这显然是因为使用了一个小技巧来释放指向构造 std::auto_ptr 的内部指针。 案例4来自This Manual

template< class Y >
auto_ptr( auto_ptr_ref<Y> m );

4) 用 m 引用的 auto_ptr 实例中保存的指针构造 auto_ptr。 p.release() 为 m 持有的 auto_ptr p 调用以获取对象的所有权。 auto_ptr_ref 是一个实现定义的类型,它包含对 auto_ptr 的引用。 std::auto_ptr 可隐式转换为该类型并可以从该类型赋值。允许实现为模板提供不同的名称或以其他方式实现等效功能。

(强调)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    相关资源
    最近更新 更多