简体   繁体   中英

Can std::set::insert() call the assignment operator?

I have a class with custom assignment operator that deliberately introduces controlled side effects.

If I have a std::set of these elements, I would like to know whether the assignment operator could be called with the use of insert .

Ie:

class A
{
public:
    A & operator=(A const & rhs)
    {
        // custom assignment operator with deliberate side effects
        // Could this be called with use of std::set::insert()?
    }
};

std::set<A> a;

// Is it possible with this, or any use of "insert", that
// the assignment operator will ever be called?

a.insert(A());

Can the assignment operator ever be called with the use of std::set::insert ?

In pre-C++11, it could, theoretically. C++11 bans it, no doubt because no implementation ever actually did it. In C++11, members of std::set don't have to support assignment. In pre-C++11, some implementations supporting concepts might have code which uses assignment, as a means of checking that your class supports it, but it should be in a non-evaluated context, so the operator will not actually be called.

The C++11 standard requires types to be used with std::set::insert to be "CopyInsertable ", "MoveInsertable" or "EmplaceConstructible" depending on the insert function you are using (23.2.3/4).

This is for example defined as:

T is EmplaceConstructible into X from args, for zero or more arguments args, means that the following expression is well-formed: allocator_traits<A>::construct(m, p, args); (23.2.1/13)

In all three cases, the default behaviour is std::allocator which uses placement new (17.6.3.5/2):

::new((void*)c)A(forward<Args>(args)...)

Depending on the insert function, in our case args is either an expression of type A , an rvalue of type A or some other arguments. But in all cases a constructor or copy constructor is used, not the assignment operator.

This is what the standard says (and GCC 4.6.3 does). Even if there is no reason to use the assignment operator, some compiler may still do it. So I would suggest don't rely too much on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM