相关疑难解决方法(0)

copy elision:在return语句中使用三元表达式时调用未调用的构造函数?

请考虑以下示例:

#include <cstdio>

class object
{
public:
    object()
    {
        printf("constructor\n");
    }

    object(const object &)
    {
        printf("copy constructor\n");
    }

    object(object &&)
    {
        printf("move constructor\n");
    }
};

static object create_object()
{
    object a;
    object b;

    volatile int i = 1;

// With #if 0, object's copy constructor is called; otherwise, its move constructor.
#if 0
    if (i)
        return b; // moves because of the copy elision rules
    else
        return a; // moves because of the copy elision rules
#else
    // Seems equivalent …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

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

标签 统计

c++ ×1

c++11 ×1