相关疑难解决方法(0)

为什么三元运算符会阻止返回值优化?

为什么三元运算符会阻止MSVC中的返回值优化(RVO)?考虑以下完整的示例程序:

#include <iostream>

struct Example
{
    Example(int) {}
    Example(Example const &) { std::cout << "copy\n"; }
};

Example FunctionUsingIf(int i)
{
    if (i == 1)
        return Example(1);
    else
        return Example(2);
}

Example FunctionUsingTernaryOperator(int i)
{
    return (i == 1) ? Example(1) : Example(2);
}

int main()
{
    std::cout << "using if:\n";
    Example obj1 = FunctionUsingIf(0);
    std::cout << "using ternary operator:\n";
    Example obj2 = FunctionUsingTernaryOperator(0);
}
Run Code Online (Sandbox Code Playgroud)

使用VC 2013编译如下: cl /nologo /EHsc /Za /W4 /O2 stackoverflow.cpp

输出:

using if:
using ternary operator: …
Run Code Online (Sandbox Code Playgroud)

c++

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

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++ ×2

c++11 ×1