Skip to content

Initializing value with lambda causes returning reference to a temporary #580

@antrv

Description

@antrv

Hi,
In my example I instantiate a value from another type. Compiler warns about
di.hpp(2458,1): warning C4172: returning address of local variable or temporary.
The code crashes. How to avoid this?

In the real code I instantiate boost::asio::io_context and call get_executor() which returns io_context::executor_type, but I convert it to any_executor which then consumed by another class.

Code:

#include <array>
#include <boost/di.hpp>
#include <boost/di/extension/scopes/shared.hpp>
#include <gtest/gtest.h>

namespace di = boost::di;

class Value
{
    std::array<int, 16> a_ {};
};

class ValueGenerator
{
public:
    Value get() const { return {}; }
};

class ValueConsumer
{
    Value value_;

public:
    explicit ValueConsumer(const Value& value)
        : value_ {value}
    {
    }
};

TEST(DITest, Example1)
{
    const auto injector = di::make_injector<di::extension::shared_config>(
        di::bind<Value>.to([](const auto& inj) -> Value {
            return inj.template create<ValueGenerator&>().get();
        })
    );

    auto& consumer = injector.create<ValueConsumer&>();
    std::ignore = consumer;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions